0

I'm messing around in a playground trying to get a multi-line UILabel to wrap itself but it won't wrap. I'd expect the label to auto-size itself. Why isn't this working?

I'd prefer not to give it an explicit height and have the label wrap it self

public func Init<Type>(_ value: Type, block: (_ object: Type) -> Void) -> Type {
    block(value)
    return value
}

let view = Init(UIView()) {
    $0.backgroundColor = .white
    $0.frame = CGRect(x: 0, y: 0, width: 375, height: 600)
}

let label = Init(UILabel()) {
    $0.text = "This is a really long string that wraps to two lines but sometimes three."
    $0.textColor = .black
    $0.numberOfLines = 0
    $0.lineBreakMode = .byWordWrapping
}

struct Style {
    static let margin: CGFloat = 12
}

view.addSubview(label)

label.sizeToFit()
label.frame.origin = CGPoint(x: 12, y: 20)
Zack Shapiro
  • 6,648
  • 17
  • 83
  • 151

1 Answers1

3

You need to constrain its width, either through it's anchors or explicitly giving it a width.

TNguyen
  • 1,041
  • 9
  • 24
  • How can I give it a width without giving it a height? Setting `.frame` with a `CGRect` won't work since it requires a height to init – Zack Shapiro Nov 21 '19 at 21:26
  • add NSLayoutConstraint for the Label Like you can add leading and trailing constraints check this https://stackoverflow.com/a/26181982/2991942 – Same7Farouk Nov 21 '19 at 21:39
  • @ZackShapiro It depends whether or not you want to do it through setting frames or whether or not you want to do it through setting constraints. If you want to do it through constraints, then refer to @Same7Farouk link above, otherwise if it's through frames then you'll need to use `sizeThatFits` – TNguyen Nov 21 '19 at 21:44
  • Great. Thanks so much – Zack Shapiro Nov 21 '19 at 21:47