Finding the correct width of a NSString
On what factors does the 开发者_如何学Pythonwrapping of the text inside a textview depends. Width of my textview is 160 px and I calculated the width of the incoming text using below mentioned code and it comes out to be 157 px but this text is wrapped in 3 lines... Why so?
CGSize size = [myText sizeWithFont:textViewFont
constrainedToSize:textView.frame.size
lineBreakMode:UILineBreakModeWordWrap];
CGFloat textWidth = size.width;
I thought of dividing width of text with width of the textview to get the number of lines. But calculation returns me 1 whereas I can see 3 lines coming in textview on simulator.
- (CGSize)sizeWithFont:(UIFont *)font
constrainedToSize:(CGSize)size
lineBreakMode:(UILineBreakMode)lineBreakMode
Calculates the size for a string if it would be drawn constrained by the size given as an argument, if the string is too long for the given size constraint it will get truncated to fit.
To get the width of the string if it's drawn on a single line with no constraints use:
- (CGSize)sizeWithFont:(UIFont *)font
see: http://developer.apple.com/library/ios/#documentation/uikit/reference/NSString_UIKit_Additions/Reference/Reference.html
NOTE: As of iOS7
- (CGSize)sizeWithFont:(UIFont *)font
is deprecated, instead use:
- (CGSize)sizeWithAttributes:(NSDictionary *)attrs
Try setting the height
of the size you pass into that method to be something huge. Otherwise the returned size will always show the actual height of the text view (assuming the full string does not fit in the given height).
精彩评论