I have 10 UILabels with different sizes, and I want to arrange them in 3 rows, and all rows have leading alignment, and if the last item of each row can't fit in remaining space of parent view, it have to move to the next line. How can I do that by using UIStackview?
Asked
Active
Viewed 116 times
1
-
6I'd recommend to use `UICollectionView` for that, it's much easier that way. – Tamás Sengel Dec 04 '17 at 09:35
-
1I agree with @the4kman, probably `UICollectionView` would be more appropriate to what are you trying to achieve. – Ahmad F Dec 04 '17 at 09:39
-
@the4kman Thank you so much – NabiMo Dec 04 '17 at 11:08
1 Answers
0
You can try to do something like that:
Your 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:
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
}
}

Vitaly Potlov
- 365
- 1
- 7
- 14
-
Thank you, but I think that this approach can't help me with moving items into next rows, because UIStackView just arrange them in one row. – NabiMo Dec 04 '17 at 11:04
-
You can create UIStackView for each line, but I think It's not a good approach. Try to use UICollectionView it's better. – Vitaly Potlov Dec 04 '17 at 11:17