sizewithfont:forwidth:linebreakmode

3

为什么这个不起作用?无论字符串的长度如何,它总是返回18。有这个主题,但没有明确的答案。

    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);

谢谢,

Todd

3个回答

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。 - Carl Veazey
完美,它有效了,非常感谢!我不明白为什么另一个调用不起作用,我要再仔细阅读文档几遍。 - ToddB

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];

查看苹果文档


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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接