JVS
JVS

Reputation: 2682

sizeToFit with maximum width

I am trying to programmatically manipulate a UILabel so that it has a dynamic width.

I found that using sizeToFit() does this exact behavior. Now as this label becomes my navigationItem.titleView. I want it to have a maximum size, which can't be extended.

It is important to fit 2 barButtonItems in the navigationItem. For instance: a backBarButton on the left, an addButton on the right.

Is there a way to change the sizeToFit() method?

Upvotes: 6

Views: 4994

Answers (2)

Faris
Faris

Reputation: 1236

to set maximum width use preferredMaxLayoutWidth than set the maximum size like that bounds.width - 120

for example:

    yourLabel.sizeToFit()
    yourLabel.numberOfLines = 0
    yourLabel.preferredMaxLayoutWidth = bounds.width - 120

Upvotes: 1

Marius Fanu
Marius Fanu

Reputation: 6669

You can use sizeThatFits: see docs here.

You have to specify a CGSize that you want to fit in.

Upvotes: 4

Related Questions