如何使用UIStackView创建动态标签

时间:2017-12-04 09:29:22

标签: ios swift xcode swift3 uistackview

我有10个不同大小的UILabel,我想将它们排成3行,并且所有行都有前导对齐,如果每行的最后一项不能适合父视图的剩余空间,则必须转到下一行。我怎么能用UIStackview做到这一点?

here's the image

1 个答案:

答案 0 :(得分:0)

您可以尝试做类似的事情:

您的ViewController

    for item in array {
        let someView = VPView(frame: CGRect(x: 0, y: 0, width: 70, height: 20))
        someView.translatesAutoresizingMaskIntoConstraints = false
        stackView.addArrangedSubview(someView)
    }

UIView类:

class VPView: UIView {

    let myLabel = UILabel()

    override init(frame: CGRect) {
        super.init(frame: frame)
        self.addLabel()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }

    func addLabels() {

        //Mark: - Styles
        let labelH: CGFloat = 15
        let labelW: CGFloat = 70

        //MARK: - My Label
        self.myLabel.frame = CGRect(x: 0, y: 0, width: labelW, height: labelH)
        self.myLabel.backgroundColor = UIColor.blue
        self.myLabel.textAlignment = NSTextAlignment.center
        self.myLabel.numberOfLines = 0
        self.addSubview(self.myLabel)

        self.myLabel.translatesAutoresizingMaskIntoConstraints = false
        self.myLabel.heightAnchor.constraint(equalToConstant: labelH).isActive = true
        self.myLabel.widthAnchor.constraint(equalToConstant: labelW).isActive = true
        self.myLabel.topAnchor.constraint(equalTo: self.topAnchor).isActive = true
        self.myLabel.leadingAnchor.constraint(equalTo: self.leadingAnchor).isActive = true

    }
}