0

I have 2 UILabels. lbl1's text can change, while lbl2's text is static.

They are both initially set on the same line. I have lbl1's numberOfLines set to 0 (infinity). I would like lbl2 to push down and align its top to lbl1's bottom when lbl1's width encroaches on lbl2's space. I have a current solution, but feel there's a pure autolayout way I'm missing. Any help would be great!

Both labels fit on 1 line:

enter image description here

lbl2 does not shift down in my attempts at pure autolayout:

enter image description here

Desired:

enter image description here

Current solution works, but feels un-ideal:

import XCPlayground
import SnapKit
import UIKit

let screen: UIView = UIView(frame: CGRectMake(0,0,320,568))
XCPlaygroundPage.currentPage.liveView = screen
XCPlaygroundPage.currentPage.needsIndefiniteExecution = true

let lbl1: UILabel = UILabel()
lbl1.text = "Short Text asnoetuha 1 1 1 1 "
lbl1.numberOfLines = 0
lbl1.backgroundColor = UIColor.whiteColor()

let lbl2: UILabel = UILabel()
lbl2.text = "Amount Text"
lbl2.backgroundColor = UIColor.yellowColor().colorWithAlphaComponent(0.5)

screen.addSubview(lbl1)
screen.addSubview(lbl2)

lbl1.snp_makeConstraints { (make: ConstraintMaker) in
  make.top.leading.equalTo(screen)
  make.width.lessThanOrEqualTo(screen.snp_width)
}

lbl2.snp_makeConstraints { (make: ConstraintMaker) in
  // Below lines feel un-ideal
  let lbl2X: CGFloat = screen.frame.width - lbl2.intrinsicContentSize().width
  let lbl1RightX: CGFloat = screen.frame.origin.x + lbl1.intrinsicContentSize().width
  let hasOverlap: Bool = lbl1RightX >= lbl2X

  make.top.equalTo(hasOverlap ? lbl1.snp_bottom : lbl1.snp_top).priorityLow()
  make.trailing.equalTo(screen)
}
mcm
  • 655
  • 9
  • 10

1 Answers1

-1

I do believe you are not approaching this the right way. You should be able to create a function that listens for when lbl1 has its right anchor come into contact with lbl2's left anchor (very easy with SnapKit).

When this does happen, you call a function that remakes the constraints to how fit the image you provided. This is done with a call to snap_updateConstraints or snp_remakeConstraints. Then your constraint code should be straight forward as you would just pin the bottom anchor of lbl1 to the top anchor of lbl2 and then just make the other constraints until you get that desired effect.

romero-ios
  • 1,075
  • 1
  • 11
  • 20