Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
367 views
in Technique[技术] by (71.8m points)

iphone - What is -[NSString sizeWithFont:forWidth:lineBreakMode:] good for?

In my question "How do I get -[NSString sizeWithFont:forWidth:lineBreakMode:] to work?", I learned that -[NSString sizeWithFont:constrainedToSize:lineBreakMode:] was actually what I needed.

The documentation for -[NSString sizeWithFont:forWidth:lineBreakMode:] states explains it doesn't actually wrap the text to additional lines. So how would I use it? (Examples would help.)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

It works great for multi line strings as well.

Basically its a function that lets you see how big a string is going to be when rendered with a font and line break mode.

I use it in a few spots in my application when I have variable length text I want to display in a certain area.

By default a UILabel will center the text vertically. To have the text top aligned you need to size the label to be only the height required by the string that's in it.

I use this method to do this.

And example of how I would use it to do that is as follows:

//Calculate the expected size based on the font and linebreak mode of your label
CGSize maximumLabelSize = CGSizeMake(296,9999);

CGSize expectedLabelSize = [yourString sizeWithFont:yourLabel.font 
                        constrainedToSize:maximumLabelSize 
                        lineBreakMode:yourLabel.lineBreakMode]; 

//adjust the label the the new height.
CGRect newFrame = yourLabel.frame;
newFrame.size.height = expectedLabelSize.height;
yourLabel.frame = newFrame;

You specify how big of an area you have to put the text in, and then this method tells you how much space it will take up (wrapping as required). Also if the string will overflow the bounds of the rect you provide you can tell and then decided how to display the text.

The reference to it not actually wrapping the text is there because this method doesn't actually do anything to the text. It just virtually lays it out and returns how big of an area it would need to really lay it out.

its the responsibility of the label (or what ever container you are using for the text) to perform the wrapping/what ever else that needs to be done.

Hope that helps.

chris.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...