ios - UIButton 高度和自动布局
问题描述
在我的一个 ViewControllers 中,我使用 UIView,底部有两个按钮。显然,我想适应屏幕的两个按钮,所以我使用这个:
leftButton.bottomAnchor.constraint(equalTo: self.bottomAnchor, constant: -16).isActive = true
rightButton.bottomAnchor.constraint(equalTo: self.bottomAnchor, constant: -16).isActive = true
//16 points between the buttons
leftButton.rightAnchor.constraint(equalTo: rightButton.leftAnchor, constant: -16).isActive = true
//right alignment for the buttons
rightButton.rightAnchor.constraint(equalTo: self.rightAnchor, constant: -16).isActive = true
//left padding for the left button - 16 points
leftButton.leftAnchor.constraint(greaterThanOrEqualTo: self.leftAnchor, constant: 16).isActive = true
//rightButton can't be less wide than 1/3 of its superview
rightButton.widthAnchor.constraint(greaterThanOrEqualToConstant: widthOfTheView / 3).isActive = true
它有效,但如果我的左按钮标题很长怎么办?我的左键变高了,没关系。但是我的右键仍然不是很高,看起来略显丑陋。
好的,但是如果我告诉自动布局我希望右侧按钮与左侧按钮具有相同的高度怎么办。
rightButton.heightAnchor.constraint(equalTo: leftButton.heightAnchor, constant: 0).isActive = true
我认为这将是一个解决方案,但我得到了这个:
从技术上讲,他们的身高是相等的,但这不是我想要的结果。
我认为,也许问题出在按钮内的 UIEdgeInsets 中,但事实并非如此(我杀了这条线,结果是一样的)。
我认为我不能在两个按钮之间选择最大高度并将其用作约束的常数,因为在此阶段它们各自的帧为零。
我尝试使用另一个 UIView 作为这两个按钮的容器,但结果是一样的。
我当然可以通过关闭自动布局并计算按钮大小和框架来解决这个问题,但我现在不想这样做。
那么,我在这里做错了什么?
解决方案
这个答案是@ DonMag的答案的延续,如果你想要一个方便的扩展来根据里面的文本调整 UIButton 的大小,那么使用下面的代码: -
extension UIButton {
func wrapContentHeight(constantValue : CGFloat) -> CGFloat {
self.titleLabel?.text = self.title(for: .normal)
self.titleLabel?.numberOfLines = 0
self.titleLabel?.frame.size.width = self.frame.width
self.titleLabel?.lineBreakMode = .byWordWrapping
self.superview?.layoutIfNeeded()
let height = self.titleEdgeInsets.top + self.titleEdgeInsets.bottom + (self.titleLabel?.frame.height ?? 45)
if height < constantValue {return constantValue}
return height
}
您可以将上述扩展应用于按钮的高度约束,如下所示:-
btnHeight.constant = selectionBtn.wrapContentHeight(constantValue: 45)
推荐阅读
- postman - 在 Postman 中使用时区
- sql-server - CDC 未公开的其他唯一索引引用列导致异常
- python - 将单个列表解析为多列
- java - 使用 java/python 关闭互斥锁
- javascript - 两个日期、年、月、日、小时、分钟之间的差异
- java - Spring:如何在使用@ControllerAdvice 注释的类中使用服务?
- node.js - 客户端没有从服务器获取下载文件
- python.net - Python.net - 远程控制 WPF 应用程序 - WPF 资源问题
- apache-kafka - 可以为每次发布添加未来回调吗?
- python - 我为合并排序编写了一个递归程序。如何通过绘制其运行时间与python中的输入图来分析它的时间复杂度