![](/img/trans.png)
[英]autolayout constraints not working correctly when adding them programmatically
[英]Swift: Autolayout programmatically bottom anchor is not working correctly
我在代碼中為我的按鈕設置了約束,這就是我的代碼的樣子:
addSubview(stackViewOne)
stackViewOne.bottomAnchor.constraint(equalTo: bottomAnchor, constant: -250).isActive = true
stackViewOne.leftAnchor.constraint(equalTo: leftAnchor, constant: 20).isActive = true
stackViewOne.rightAnchor.constraint(equalTo: rightAnchor, constant: -20).isActive = true
stackViewOne.heightAnchor.constraint(equalToConstant: frame.size.height * 0.065).isActive = true
但現在我的底錨有問題。 我想從底部使我的stackview 80。 只有當我輸入八十作為距離時,我的堆棧視圖才會顯示。 只有當我在負范圍內輸入一個非常高的值時,才會顯示堆棧視圖。 (等於:bottomAnchor,常量:-250)
有誰知道為什么? 此致
您通常不需要在 stackview 上指定高度約束 - stackview 本身將通過其排列的子視圖(標簽?)來調整大小。 我將首先刪除該約束。 確保您排列的子視圖具有大小,並且您的堆棧視圖的間距/對齊等配置正確。
也可能 safeArea / layoutMargins 干擾您的布局 - 但如果沒有更多代碼就不可能知道。
I created a UIView class and there I created objects look: import UIKit `` class TimerSequenzeView: UIView {
lazy var plusButton: UIButton = {
let btn = UIButton(type: .system)
btn.setTitle("5", for: .normal)
btn.titleLabel?.font = .systemFont(ofSize: 35)
btn.titleLabel?.font = UIFont(name: "Arial", size: 35)
btn.setTitleColor(.red, for: .normal)
btn.layer.borderColor = UIColor.red.cgColor
btn.layer.borderWidth = 3
btn.layer.cornerRadius = 30
btn.setImage(UIImage(systemName: "plus"), for: .normal)
btn.tintColor = .red
btn.translatesAutoresizingMaskIntoConstraints = false
return btn
}()
lazy var minusButton: UIButton = {
let btn = UIButton(type: .system)
btn.setTitle("5", for: .normal)
btn.titleLabel?.font = .systemFont(ofSize: 35)
btn.titleLabel?.font = UIFont(name: "Arial", size: 35)
btn.setTitleColor(.red, for: .normal)
btn.layer.borderColor = UIColor.red.cgColor
btn.layer.borderWidth = 3
btn.layer.cornerRadius = 30
btn.setImage(UIImage(systemName: "minus"), for: .normal)
btn.tintColor = .red
btn.translatesAutoresizingMaskIntoConstraints = false
return btn
}()
lazy var stackViewOne: UIStackView = {
let stackView = UIStackView()
stackView.axis = .horizontal
stackView.distribution = .fillEqually
stackView.spacing = 20
stackView.translatesAutoresizingMaskIntoConstraints = false
stackView.addArrangedSubview(plusButton)
stackView.addArrangedSubview(minusButton)
return stackView
}()
override init(frame: CGRect) {
super.init(frame: frame)
setConstrains()
}
required init?(coder: NSCoder) {
super.init(coder: coder)
}
func setConstrains() {
addSubview(stackViewOne)
stackViewOne.bottomAnchor.constraint(equalTo: safeAreaLayoutGuide.bottomAnchor, constant: -80).isActive = true
stackViewOne.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 20).isActive = true
stackViewOne.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -20).isActive = true
stackViewOne.heightAnchor.constraint(equalToConstant: frame.size.height * 0.065).isActive = true
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.