[英]How do I programatically resize a UIButton that already has constraints?
我有一个UIButton,我将其设置为从视图的左侧起8个点,从视图底部起8个点。 我目前将宽度和高度设置为> = 32点。
但是,我希望按钮在较大的显示器上更大。 我研究了如何设置约束,以使按钮始终保持相同的宽高比(在我的情况下为正方形)且始终为其父视图宽度的10%,但这意味着旋转设备时按钮会变得越来越大随着视图变得越来越宽和越来越窄,我不希望这样。 我希望它是最短边的10%。
在随附的ViewController代码中很容易获得我想要的宽度:
let buttonWidth = 0.1 * (self.view.bounds.width < self.view.bounds.height ? self.view.bounds.width : self.view.bounds.height)
但是,如何正确地将其应用于按钮,以及情节提要中应设置哪些约束? 整个界面当前在情节提要中定义。
我可以直接更新边界吗? 有约束吗? 多重约束? 在约束的情况下,我完全不熟悉如何在代码中处理它们。
仅使用情节提要板就无法实现所需的内容,因为您希望选择屏幕的最小一侧并获得10%的空间。 在代码中,您可以轻松地做到这一点。
let buttonWidth = 0.1 * min(self.view.bounds.width, self.view.bounds.height)
self.yourWidthConstraint.constant = buttonWidth
self.view.layoutIfNeeded()
尝试这个:
your_button.frame.size.width = buttonWidth
或者您可以添加/更改约束:
let widthConstraint = NSLayoutConstraint (item: your_button, attribute: NSLayoutAttribute.Width, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1, constant: buttonWidth)
your_button.view.addConstraint(widthConstraint)
我认为您应该探索Apple的大小类API。 您可以在Interface Builder中为所有特定情况设置按钮约束,例如,越来越小的设备(纵向和横向)。
此处有更多详细信息: 关于为多个大小的类进行设计
编辑 :如果要在旋转设备时保持相同的宽度/高度,请忽略情节提要中的宽度约束(但将宽高比保持为1)。 以编程方式创建宽度约束,如下所示:
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
// Equivalent: Width of self.button equals 0.1 * width of self.view
let widthConstraint = NSLayoutConstraint(item: self.button,
attribute: NSLayoutAttribute.Width,
relatedBy: NSLayoutRelation.Equal,
toItem: nil,
attribute: NSLayoutAttribute.NotAnAttribute,
multiplier: 1.0,
constant: 0.1 * CGRectGetWidth(self.view.bounds))
self.view.addConstraint(widthConstraint)
self.view.layoutIfNeeded()
}
如果创建宽度常量和宽高比约束,则宽度不会变窄。
Ctrl +拖动按钮到内容视图,然后选择“等于宽度”。 然后使用乘数= 0.1编辑该约束。 因此,您的按钮宽度始终等于设备宽度的10%。
然后创建一个宽高比约束,按钮将不会变窄。
如果您的按钮有约束,则需要通过以下方式找到它:
button.superview?.constraints.forEach { constraint in
if constraint.firstItem === button &&
constraint.firstAttribute == .width {
constraint.constant = 20
return
}
}
self.view.layoutIfNeeded()
或者,您可以为约束创建一个IBOutlet并更改其常数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.