0

I got two labels, they are supposed to be positioned in one line like the following image if their total width is not too large. (less than the screen width).
enter image description here.

Or they should be positioned in two lines. (they can't fit in one line).

enter image description here

Is it possible to implement that without dynamic calculate labels' width but use Autolayout only?

Thanks in advance.

anb
  • 123
  • 4
  • 2
    you can achieve it using a horizontal stack view. – HardikS Jan 17 '20 at 08:51
  • no, directly it's not possible – SPatel Jan 17 '20 at 08:52
  • Whatever pure autolayout solution that you come up with would be **nasty**. Because the label can come into two axises. Horizontal and Vertical. Hence you'd need to two sets of constraints. Really just don't. I think collectionViews is the right approach. – Honey Aug 31 '20 at 13:55

2 Answers2

0

It doesn't seem doable using autolayout alone. If you don't want to create views based on computations in code then only way to do something like that will probably be UICollectionView.

It would probably be overkill, but only way to do something like that seems to be a collection view with vertical scroll direction (you can turn off scrolling and bouncing if it will always fit the screen).

Only element of collection view cell would be UILabel, and for width of this cell I suggest to use answer from here https://stackoverflow.com/a/23135433/7183675 (or just use UICollectionViewFlowLayout.automaticSize if developing for iOS 10.0 or higher, this answer may be helpful for that case: https://stackoverflow.com/a/31279726/7183675)

Good luck!

Adam Tucholski
  • 927
  • 8
  • 26
-1

for better way, you can use UIStackview with horizontal or vertical alignment

private static let dynamicLabel1: UILabel = {
        let label = UILabel()
        label.textAlignment = .center
        label.numberOfLines = 0
        label.translatesAutoresizingMaskIntoConstraints = false
        label.textColor = .black
        return label
    }()

private static let dynamicLabel2: UILabel = {
            let label = UILabel()
            label.textAlignment = .center
            label.numberOfLines = 0
            label.translatesAutoresizingMaskIntoConstraints = false
            label.textColor = .black
            return label
        }()

func addStackview() {
     let stackView = UIStackView()
     stackView.axis = .vertical
     stackView.distribution = .fill
     stackView.spacing = 2
     stackView.translatesAutoresizingMaskIntoConstraints = false
     stackView.addArrangedSubview(dynamicLabel1)
     stackView.addArrangedSubview(dynamicLabel2)
}