我正在尝试使用按钮将视图添加到StackView中:
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var stackOutlet: UIStackView!
@IBOutlet weak var buttonOutlet: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func buttonAction(_ sender: AnyObject) {
let newView = UIView(frame: CGRect(x: 0, y: 0, width: 240, height: 128))
newView.heightAnchor.constraint(equalToConstant: 128)
newView.widthAnchor.constraint(equalToConstant: 240)
newView.backgroundColor = UIColor.green
stackOutlet.addArrangedSubview(newView)
stackOutlet.heightAnchor.constraint(equalToConstant: stackOutlet.frame.size.height + 128)
print(stackOutlet.subviews.count)
}
}
子视图的数量正在增加,但是屏幕上没有任何变化。我怀疑我的StackView无法正确调整大小吗?
最佳答案
没关系,我找到了解决方案:
newView.widthAnchor.constraint(equalToConstant: 240).isActive = true
newView.heightAnchor.constraint(equalToConstant: 128).isActive = true
您需要.isActive = true