Zack Shapiro
Zack Shapiro

Reputation: 6998

Multiline text label not wrapping in Swift

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)

Upvotes: 0

Views: 1290

Answers (1)

TNguyen
TNguyen

Reputation: 1051

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

Upvotes: 3

Related Questions