sizeToFit with maximum width
Asked Answered
R

2

6

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?

Renfrow answered 17/5, 2016 at 13:1 Comment(3)
you can calculate width as per position & size of both buttonMilitia
Does the adjustsFontSizeToFitWidth property of UILabel help?Spectroscope
Thanks and @Spectroscope I have set a fixed maxSize and used adjustFontSizeToFitWidth!Renfrow
W
4

You can use sizeThatFits: see docs here.

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

Whiteman answered 17/5, 2016 at 14:11 Comment(0)
B
1

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
Balder answered 5/10, 2018 at 22:45 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.