向UIStackView动态添加视图

6
我试图动态地向UIStackView添加视图(或按钮)。
首先,UIStackView没有排列的视图(垂直),在从某些HTTP响应中获取后,将多个视图(按钮)添加到UIStackView中。 UIStackView也是自动布局以容纳特定区域。我尝试找到动态添加示例,但失败了。
有人可以给我展示将视图动态添加到UIStackView的示例吗?

不确定那会不会起作用,我想我曾经尝试过一次但失败了。 - Abdul Ahmad
1
你目前做了什么? - iVarun
你解决了你的问题吗?如果是,请从下面选择一个答案。 - ekscrypto
所有的回答都受到欣赏,但没有一个完全符合我的需求。不过我必须选择一个吗? - GT Kim
3个回答

8
可能会对你有所帮助。请遵循以下要点:
  • Add UIScrollView to your UIViewController in storyboard or XIB.
  • Initiate an NSMutableArray name it arrViews gets server response and adds view in the array.
  • Initialise UIStackViewpass arrView array in the init method.
  • After that UIStackView will be added subview of UIScrollView.
  • Add constraint programmatically to UIStackView. That's it.

    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
    
希望这能帮到你,愉快编码 :)

谢谢。好建议。我一点也没想到那个滚动视图。我会尝试的。 - GT Kim
欢迎。如果这对您有用,请让我知道并接受答案并给我投票。;)以便更多帮助。 - iamVishal16

5

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

    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)
    }

谢谢!但是由于我的技术不好,我无法理解你的内容。 - GT Kim
这是一个循环,用音乐分区和乐器信息填充两个堆栈视图。重要的部分是addArrangedSubview。 - ekscrypto
1
我通过使用addArrangedSubview能够动态地将视图添加到StackView中 - 谢谢。 - Omaer

-1

在尝试了一些答案后,我偶然发现了如何解决它。

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

其中的子视图没有任何约束。

谢谢。enter image description here


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接