uiviewswift3autolayoutanchorpoint

Swift 3 how to anchor bottom when width is exceeded


I am coding an app and I want to know how I can anchor a view to the bottom instead of right side of the previous view when total width in the same row exceeds device width.

Basically like this:

View 1: width=150 anchor to superview's leftAnchor
View 2: width=500 anchor to view1's rightAnchor
View 3: width=1000 anchor to view1's bottomAnchor because total width in same row
exceeds device width

#device width=1200

Any help is appreciated. Sorry for bad English, not a native speaker.

Ps. all heights are same, width is dynamic


Solution

  • The main challenge was I couldn't know the width of my views until they are constrained.

    So I used swift's estimation.

    let size = CGSize(width: UIScreen.main.bounds.width, height: 50)
    let attributeHeight = [NSFontAttributeName: UIFont.preferredFont(forTextStyle: .subheadline)]
    let estimatedHeight = NSString(string: _title).boundingRect(with: size, options: .usesLineFragmentOrigin, attributes: attributeHeight, context: nil)
    self._estimatedWidth = estimatedHeight.width + 32
    

    after that it was easy to anchor them according to my needs with a for loop