简体   繁体   中英

auto-change size of label depending on text

I have a label and I want to adjust it's appearance. I want it to be in the center of the screen and as wide as it needs to be for the text inside. So my goal is to change the text in code manually, but the width shall change on it's own depending on the length of the text. Is there a way doing so?

I tried the following but it did not work...

MessageLabel.frame = CGRectMake(self.view.center.x, self.view.center.y, self.frame.size.width, self.frame.size.height)

but the first part does work as I checked by changing the width & height to some numbers:

MessageLabel.frame = CGRectMake(self.view.center.x, self.view.center.y, 100, 30)

thanks in advance :)

You can use auto layout to achieve this. You just need two constraints to center label on screen. You can put this in viewDidLoad() Here is the code:

let centerXConstraint = NSLayoutConstraint(item: MessageLabel, attribute: .CenterX, relatedBy: .Equal, toItem: self.view, attribute: .CenterX, multiplier: 1.0, constant: 0.0)
let centerYConstraint = NSLayoutConstraint(item: MessageLabel, attribute: .CenterY, relatedBy: .Equal, toItem: self.view, attribute: .CenterY, multiplier: 1.0, constant: 0.0)

self.view.addConstraints([centerXConstraint, centerYConstraint])

EDIT: Also you need to call this in same method:

MessageLabel.setTranslatesAutoresizingMaskIntoConstraints(false)

Since it sounds like you want to add your labels programmatically, this is what I do to calculate the height of a label given a fixed width. I know you said you want the opposite, so I updated my code below to take an argument of height.

func getStringSize(str: String, containerHeight: CGFloat) -> CGRect {

        var thisStr:NSString = str

        var boundingBox = thisStr.boundingRectWithSize(
            CGSizeMake(
                CGFloat(MAXFLOAT),
                containerHeight
            ),
            options: NSStringDrawingOptions.UsesLineFragmentOrigin, attributes: nil, context: nil
        )

        return boundingBox
    }

So, to see it in action, you can get the width by doing:

var labelWidth: CGFloat = getStringSize("Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris posuere ipsum urna, quis pharetra.", 300px).bounds.width

Then, you can create your label with all your variables (width, height, x, y) known.

Make sense?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM