Set UILabel to autostart content size in iOS

I am trying to understand basic dynamic layout using native content size. As the picture shows, I have two UILabels in the horizontal direction, which will be my default layout. How to make layout constraints so that

  • If the size of the contents of either of the two labels is larger than the other, it should be placed on a vertical stack
  • In addition, if the size of the contents of two labels is more than one line, how can we make text that satisfies the vertical layout

AutoLayout

+4
source share
2 answers

stackView intrinsicContentSize UIScreen.main.bounds.width stackView.

if (label1.intrinsicContentSize.width + label2.intrinsicContentSize.width) > (UIScreen.main.bounds.width - 48/* 48 is the left and right margins*/) {
     stackView.axis = .vertical
}else {
     stackView.axis = .horizontal
}

numberOfLines 0.

+1

.

  • L1 L2 firstLabel secondLabel,
  • L1
  • L1
  • L1 >= someValue
  • L1 >= someValue 999
  • L2 L1, nsconstraint
  • L2 L1, nsconstraint
  • L2 L1, nsconstraint.
  • L2 L1, nsconstraint.
  • L2 >= someValue
  • L2 >= someValue 999

        let firstWidth : CGFloat = (firstLabel?.intrinsicContentSize.width)!
    let secondWidth : CGFloat = (secondLabel?.intrinsicContentSize.width)!
    
    if (firstWidth + secondWidth) <= self.view.frame.size.width - 45.0 {
    
         secondLabelLeadingConstraintTofirstLabelLeading?.priority = UILayoutPriority(rawValue: 250)
         secondLabelSpacingConstraintTofirstLabel?.priority = UILayoutPriority(rawValue: 1000)
         secondLabelTopConstraintTofirstLabelTop?.priority = UILayoutPriority(rawValue: 1000)
         secondLabelTopConstraintTofirstLabelBottom?.priority = UILayoutPriority(rawValue: 250)
    
    }
    else {
    
        secondLabelLeadingConstraintTofirstLabelLeading?.priority = UILayoutPriority(rawValue: 1000)
        secondLabelSpacingConstraintTofirstLabel?.priority = UILayoutPriority(rawValue: 250)
        secondLabelTopConstraintTofirstLabelTop?.priority = UILayoutPriority(rawValue: 250)
        secondLabelTopConstraintTofirstLabelBottom?.priority = UILayoutPriority(rawValue: 1000)
    
    }
    
0

Source: https://habr.com/ru/post/1694445/


All Articles