【问题标题】:Can the size for -[NSString drawInRect:] be determined by the string's content?-[NSString drawInRect:] 的大小可以由字符串的内容确定吗?
【发布时间】:2013-06-11 22:50:31
【问题描述】:

我的代码中有一个名为theString 的长字符串,我将其传递给drawRect: 方法以在屏幕上绘制。

    -(void)drawRect:(CGRect)rect
{
    [super drawRect:rect];
    [theString drawInRect:CGRectMake(0, 0, self.bounds.size.width, 200)]; 
}

如您所见,我可以将宽度设置为屏幕大小,但高度必须手动设置,当传递的字符串长度不同时,这是一个问题。如何自动检测框架需要的高度?同样在未来我可能会扩展它以包含不同字体样式的属性字符串,因此计算字符可能不是一个很好的选择。

【问题讨论】:

标签: ios cocoa-touch graphics nsstring


【解决方案1】:

您可以做的是获取您的文本将具有的字体

UIFont *myFont = [UIFont fontWithName:@"SOME_NAME" size:16];

然后使用NSString的方法sizeWithFont:,像这样:

CGSize theStringSize = [theString sizeWithFont:myFont];

最后,设置字符串的宽度和高度:

[theString drawInRect:CGRectMake(0, 0, theStringSize.width, theStringSize.height)];

希望这会有所帮助!

【讨论】:

  • 是的,不幸的是,这是我的问题,文本最终将是一整页的文本,其中包含标题、不同大小的字体等,因此使用 sizeWithFont 将无法正常工作吗?
【解决方案2】:

您可以通过RTLabel 进行操作。从此链接下载RTLabel.h

RTLabel.m

通过以下方式使用它: 将文本设置为RTLabel 对象,它还将处理HTML 字符串并获得RTLabel 对象的大小,这将是您的文本的大小。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-22
    • 2017-08-10
    • 2011-05-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多