sizewithfont:forwidth:linebreakmode

时间:2012-09-05 02:39:37

标签: iphone objective-c ios nsstring

为什么这不起作用?无论弦的长度如何,它总是返回18。有this thread,但不是明确的答案。

    NSString * t = @"<insert super super long string here>";

    CGSize size = [t sizeWithFont:[UIFont systemFontOfSize:14.0] forWidth:285 lineBreakMode:UILineBreakModeWordWrap];

    NSLog(@"size.height is %f and text is %@", size.height, t);

谢谢,

托德

3 个答案:

答案 0 :(得分:5)

改为使用sizeWithFont:constrainedToSize:lineBreakMode:

NSString * t = @"<insert super super long string here>";
CGSize constrainSize = CGSizeMake(285, MAXFLOAT);
CGSize size = [t sizeWithFont:[UIFont systemFontOfSize:14.0] constrainedToSize:constrainSize lineBreakMode:UILineBreakModeWordWrap];
NSLog(@"size.height is %f and text is %@", size.height, t);

答案 1 :(得分:1)

已弃用的方法:NS_DEPRECATED_IOS(2_0,7_0)

- (CGSize)sizeWithFont:(UIFont *)font forWidth:(CGFloat)width lineBreakMode:(NSLineBreakMode)lineBreakMode NS_DEPRECATED_IOS(2_0, 7_0, "Use -boundingRectWithSize:options:attributes:context:");

实施例

CGSize titleTextSize = [self.titleLabel.text sizeWithFont:self.myLabel.font forWidth:myLabelWidth lineBreakMode:NSLineBreakByTruncatingTail];

新方法

使用:

- (CGRect)boundingRectWithSize:(CGSize)size
                       options:(NSStringDrawingOptions)options
                    attributes:(NSDictionary<NSString *,
                                        id> *)attributes
                       context:(NSStringDrawingContext *)context

示例:

 // Create a paragraph style with the desired line break mode
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    paragraphStyle.lineBreakMode = NSLineBreakByTruncatingTail;

    // Create the attributes dictionary with the font and paragraph style
    NSDictionary *attributes = @{
                                 NSFontAttributeName:self.myLabel.font,
                                 NSParagraphStyleAttributeName:paragraphStyle
                                 };

    // Call boundingRectWithSize:options:attributes:context for the string
    CGRect textRect = [self.countLabel.text boundingRectWithSize:CGSizeMake(widthOfMyLabel, 999999.0f)
                                           options:NSStringDrawingUsesLineFragmentOrigin
                                        attributes:attributes
                                           context:nil];

See Appple Doc

答案 2 :(得分:0)

CGSize size = [t sizeWithFont:[UIFont fontWithName:@"Arial-BoldMT" size:16.0] constrainedToSize:CGSizeMake(220,500) lineBreakMode:UILineBreakModeWordWrap];