ios - addArrangedSubview 并调整 StackView 的大小

标签 ios swift uistackview

我正在尝试使用按钮将 View 添加到 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)
    }
}

subview 的数量在增加,但屏幕上没有任何变化。我怀疑我的 StackView 没有正确调整大小,对吗?

最佳答案

没关系,我找到了解决方案:

newView.widthAnchor.constraint(equalToConstant: 240).isActive = true
newView.heightAnchor.constraint(equalToConstant: 128).isActive = true

您需要 .isActive = true

关于ios - addArrangedSubview 并调整 StackView 的大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39151280/

相关文章:

ios - NSFileManager 移动文件显示错误

swift - 使用 iOS 中的事件填充 tableView (swift)

SWIFT:控制另一个用户设备上的 View

ios - 如何在 Swift 中显示动态高度的 3*3 CollectionView 单元格

ios - 当所有 subview 都隐藏在动画 block 中时,UIStackView 将其排列的 subview 移动到左上角

swift - 在 stackview 中隐藏 View 仍然保持约束事件

ios - 将 subview 添加到 uistackview 不适用于按钮单击

html - 苹果触摸图标是否必须位于根文件夹中?

ios - segue 后强制刷新 View

ios - 如何在 Swift 编程中获得基于导航的模板功能