我尝试使用按钮向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没有正确调整大小吗?
答案 0 :(得分:3)
没关系我找到了解决方案:
newView.widthAnchor.constraint(equalToConstant: 240).isActive = true
newView.heightAnchor.constraint(equalToConstant: 128).isActive = true
您需要.isActive = true