我目前在iPhone X上使用约束时遇到一些问题。我想使按钮超出安全区域并更改其高度,但我不能。
所以,我继续改变我之前定义的高度限制:
heightConstaintBtn.constant = 73.0
但是按钮位于安全区域上方,并且没有我想要的高度。
我很高兴看到有人可以帮助我。
PS:如果您知道如何不受限制地调整按钮的大小,请告诉我。谢谢
进行自动布局有时可能会很复杂
在ViewDidLoad
中设置所有这些代码首先声明您的按钮
let confirmBtn: UIButton = {
let confirmBtn = UIButton(type: UIButtonType.custom)
confirmBtn.frame = CGRect.zero
confirmBtn.backgroundColor = UIColor.green //set your color
confirmBtn.setAttributedTitle(NSAttributedString(string: "confirm", attributes: [NSAttributedStringKey.font : UIFont(name: "HelveticaNeue-Bold", size: 15)!, NSAttributedString.Key.foregroundColor : UIColor.white]), for: UIControlState.normal)
confirmBtn.layer.cornerRadius = 5.0
confirmBtn.translatesAutoresizingMaskIntoConstraints = false
return confirmBtn
}()
如果您想要按钮超出safeArea,则不建议这样做,这就是存在SafeArea的原因
view.addSubview(confirmBtn) //add to subview
设置约束条件
NSLayoutConstraint.activate([
confirmBtn.leadingAnchor.constraint(equalTo: self.leadingAnchor),
confirmBtn.trailingAnchor.constraint(equalTo: self.trailingAnchor),
confirmBtn.bottomAnchor.constraint(equalTo: self.bottomAnchor),
confirmBtn.heightAnchor.constraint(equalTo: self.heightAnchor, multiplier: 0.1)
])
其中LeadingAnchor是要告诉应用程序在右侧设置的屏幕右侧
TrailingAnchor在左侧
[BottonAnchor是应用程序的botton如果您要使用安全区域,请使用此
confirmBtn.bottomAnchor.constraint(equalTo: self.safeAreaLayoutGuide.bottomAnchor)
因此,您使用的bottonAnchor将会位于屏幕上方安全区域之外的底部
最后,您只需要设置heightAnchor
,请记住,如果您使用乘数1表示屏幕的100%,即使用0.1表示屏幕的10%
我认为此示例应为您提供帮助,请检查。
let confirmBtn: UIButton = {
let confirmBtn = UIButton(type: .custom)
confirmBtn.backgroundColor = .green
confirmBtn.translatesAutoresizingMaskIntoConstraints = false
return confirmBtn
}()
var heightConstraint: NSLayoutConstraint?
view.addSubview(confirmBtn)
confirmBtn.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true
confirmBtn.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true
confirmBtn.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
heightConstraint = confirmBtn.heightAnchor.constraint(equalToConstant: 60)
heightConstraint?.isActive = true
/// update height
heightConstraint?.constant = 300
我认为您必须打电话
self.view.layoutIfNeeded()