动态添加视图到 UIStackview

Adding views dynamically to UIStackview

我正在尝试向 UIStackView 动态添加视图(或按钮)。

起初,UIStackView没有排列视图(垂直),并且 从一些 http 响应中获取后,几个视图(按钮)被添加到 UIStackViewUIStackView 也是自动布局以容纳特定区域。 我试图找到动态添加示例,但失败了。

任何人都可以向我展示在 UIStackView 上动态添加视图的示例吗?

我在我的一个项目中使用了这段代码:

    let baseFrame = CGRect(origin: .zero, size: CGSize(width: requiredWidth, height: partitionHeight))
    for instrument in instruments {
        let partitionView = PartitionOnDemand(instrument: instrument, mode: playbackMode, frame: baseFrame, referenceView: partitionsAnimator)
        partitionsStackView.addArrangedSubview(partitionView)
        let tab = InstrumentInfoTabContainer.instantiate(with: instrument) {
            self.focus(on: instrument)
        }
        tabsStackView.addArrangedSubview(tab)
    }

可能对你有帮助。请遵循以下几点:

  • UIScrollView 添加到故事板或 XIB 中的 UIViewController
  • 启动一个 NSMutableArray 命名它 arrViews 获取服务器响应并在数组中添加视图。
  • 初始化 UIStackView在 init 方法中传递 arrView 数组。
  • 之后 UIStackView 将添加 UIScrollView 的子视图。
  • 以编程方式向 UIStackView 添加约束。就是这样。

    if let response = self.serverResponse {
        if let body = response.responseBody {
    
            if let view = body.views {
                arrViews =  createSubViews(view)
            }
    
        }
    }
    
    let stackView = UIStackView(arrangedSubviews: arrViews)
    stackView.translatesAutoresizingMaskIntoConstraints = false
    stackView.axis = .vertical
    stackView.spacing = 16
    stackView.distribution = .fill
    self.scrollView.addSubview(stackView)
    
    //constraints
    
    let leading = NSLayoutConstraint(item: stackView, attribute: .leading, relatedBy: .equal, toItem: self.scrollView, attribute: .leading, multiplier: 1.0, constant: 0)
    self.scrollView.addConstraint(leading)
    let trailing = NSLayoutConstraint(item: stackView, attribute: .trailing, relatedBy: .equal, toItem: self.scrollView, attribute: .trailing, multiplier: 1.0, constant: 0)
    self.scrollView.addConstraint(trailing)
    let top = NSLayoutConstraint(item: stackView, attribute: .top, relatedBy: .equal, toItem: self.scrollView, attribute: .top, multiplier: 1.0, constant: 0)
    self.scrollView.addConstraint(top)
    
    let bottom = NSLayoutConstraint(item: stackView, attribute: .bottom, relatedBy: .equal, toItem: self.scrollView, attribute: .bottom, multiplier: 1.0, constant: 0)
    self.scrollView.addConstraint(bottom)
    
    let equalWidth = NSLayoutConstraint(item: stackView, attribute: .width, relatedBy: .equal, toItem: self.scrollView, attribute: .width, multiplier: 1.0, constant: 0)
    
    self.scrollView.addConstraint(equalWidth)
    
    
    leading.isActive = true
    trailing.isActive = true
    top.isActive = true
    bottom.isActive = true
    equalWidth.isActive = true
    

希望对您有所帮助。编码愉快:)

在尝试寻找答案时,我碰巧找到了解决方法。

class ViewController: UIViewController {

@IBOutlet weak var stack: UIStackView!
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 onBtn_Create(_ sender: Any) {
    createButton("new button ...")
}
@IBAction func onBtn_Delete(_ sender: Any) {
    if let v = stack.arrangedSubviews.last {
        stack.removeArrangedSubview(v)
        v.removeFromSuperview()
    }

}


func createButton(_ title: String) {
    let button = UIButton()
    button.frame = CGRect(x: 0, y: 0, width: 100, height: 100)
    button.backgroundColor = UIColor.blue
    button.setTitle(title, for: .normal)
    button.addTarget(self, action: #selector(buttonAction), for: .touchUpInside)

    stack.addArrangedSubview(button)
}


@objc func buttonAction(sender: UIButton!) {
    print("Button tapped")
}

}

并且,我锚定到 UIStackView,Trailing=0,Leading=0,Top=0,Bottom=8 到 TextView.Top

里面的子视图完好无损

谢谢。