如何使用数组以编程方式在堆栈视图中添加多个按钮

时间:2019-03-29 05:03:12

标签: ios swift swift4

我使用了DLRadioButton库。我需要使用字符串数组在垂直堆栈视图中添加多个按钮,然后加载到堆栈视图中。

override func viewDidLoad() {
        super.viewDidLoad()
    for item in 0...3{
        AccountStackView(at: item).setTitle("\(account[item])", for: .normal)
    }
}
func AccountStackView(at index:Int) -> DLRadioButton {
    return StackView.arrangedSubviews[index] as! DLRadioButton
}

1 个答案:

答案 0 :(得分:1)

在您的UIViewController中添加

override func viewDidLoad() {
    super.viewDidLoad()
    let array = [dLRadioButton0, dLRadioButton1, dLRadioButton2, dLRadioButton3] // change it if you already have an array of DLRadioButton buttons

    for item in array {
        item.setTitle("Your Text", for: .normal)
    }

    let yourStackView = addToStackViewButtons(array: array, andAddTo: self.view)
    for item in yourStackView.arrangedSubviews as! [DLRadioButton] {
        // do something with your DLRadioButton's
        item.backgroundColor = .green
    }
}

func addToStackViewButtons(array : [DLRadioButton], andAddTo yourView : UIView) -> UIStackView {
    let sv = UIStackView(arrangedSubviews: array) // or just get link from storyboard via outlet link
    sv.distribution = .fillEqually
    sv.axis = .vertical

    sv.frame = yourView.frame
    yourView.addSubview(sv) // if you create stackview sv programmically

    // set frame of add your constraints if you need
    // for example:
    sv.leftAnchor.constraint(equalTo: yourView.leftAnchor)
    sv.topAnchor.constraint(equalTo: yourView.topAnchor)
    sv.bottomAnchor.constraint(equalTo: yourView.bottomAnchor)
    sv.rightAnchor.constraint(equalTo: yourView.rightAnchor)
    return sv
}