我怎样才能获得将绘制子字符串的绑定矩形?

时间:2013-01-23 12:14:19

标签: ios nsstring

我希望得到一个框,其中NSString的某个子字符串已经在UILabel(或UITextView,如果更容易)中呈现,考虑到绘制整个NSString的rect,推出换行模式在OSX中,在添加中,有一个返回rect

的方法
- (NSRect)boundingRectWithSize:(NSSize)size options:(NSStringDrawingOptions)options attributes:(NSDictionary *)attributes

iOS有类似的东西吗?我检查了文档,但我没有找到任何东西。那里有类似的东西吗?

1 个答案:

答案 0 :(得分:2)

我想,这可能会对你有帮助

// Create some text view for example
_tv = [[UITextView alloc] initWithFrame:CGRectMake(10.0, 10.0, 300.0f, 250.0f)];
_tv.text = @"dkjshfk shf kjhs fkj ewkjhf kwfwkj fhwk fwh fjkw hfjkhwe fkjwh";
_tv.font = [UIFont systemFontOfSize:24];
[self.view addSubview:_tv];

这就是你要找的东西

- (void)someAction:(id)sender
{
    // Here is a frame of selected text in text view
    CGRect frame = [_tv firstRectForRange:_tv.selectedTextRange];

    // Mark selected text with yellow
    UIView *v = [[[UIView alloc] initWithFrame:frame] autorelease];
    v.backgroundColor = [UIColor yellowColor];
    v.alpha = .8f;
    [_tv addSubview:v];
}