【问题标题】:How can I create dynamic labels using UIStackView如何使用 UIStackView 创建动态标签
【发布时间】:2017-12-04 09:29:22
【问题描述】:

我有 10 个不同大小的 UILabel,我想将它们排列成 3 行,并且所有行都有前导对齐,如果每行的最后一项无法放入父视图的剩余空间,则必须移动到下一行。我怎样才能通过使用 UIStackview 做到这一点?

【问题讨论】:

  • 我建议使用UICollectionView,这样更容易。
  • 我同意@the4kman,可能UICollectionView 更适合您想要实现的目标。
  • @the4kman 非常感谢

标签: ios swift xcode swift3 uistackview


【解决方案1】:

你可以尝试做这样的事情:

你的视图控制器

    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

    }
}

【讨论】:

  • 谢谢,但我认为这种方法无法帮助我将项目移动到下一行,因为 UIStackView 只是将它们排列在一行中。
  • 您可以为每一行创建 UIStackView,但我认为这不是一个好方法。尝试使用 UICollectionView 会更好。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-07
  • 2016-11-23
  • 1970-01-01
  • 2020-09-22
相关资源
最近更新 更多