【问题标题】:How could I get the bound rect in which a substring will be drawn?我怎样才能获得将在其中绘制子字符串的绑定矩形?
【发布时间】:2013-01-23 12:14:19
【问题描述】:

我想得到一个框,其中一个 NSString 的某个子字符串已经在 UILabel(或 UITextView,如果更容易的话)中呈现,考虑到整个 NSString 被绘制的矩形,采用换行模式,字体等。在OSX中,在添加中,有一个方法可以返回那个rect

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

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

【问题讨论】:

    标签: ios nsstring


    【解决方案1】:

    我想,这可能对你有帮助

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

    【讨论】:

    • 感谢您的回复,但这不是我想要的。我想要已经在 UILabel(或 UITextView)中呈现的字符串的子字符串的矩形。我将编辑问题以澄清。
    • 现在,我明白了。这是另一个建议 CGRect frame = [_tv firstRectForRange:_tv.selectedTextRange];
    • 谢谢,除非有表情符号,否则它可以工作,在这种情况下,如果它在表情符号之后,它不会返回给定范围内的矩形。你有什么线索吗?也许是编码问题?
    • 我对此没有任何问题。但是,The first rectangle in a range of text. You might use this rectangle to draw a correction rectangle. The “first” in the name refers the rectangle enclosing the **first** line when the range encompasses multiple lines of text. 所以,我们需要第二个矩形,即当前选择的结束位置。它的名字caretRectForPosition: - 返回插入符号的矩形,CGRect frameEnd = [_tv caretRectForPosition:_tv.selectedTextRange.end];。仍然需要组合两个矩形以获得完整的选择矩形。这是我得到的image link
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-12-14
    • 1970-01-01
    • 2014-12-14
    • 1970-01-01
    • 1970-01-01
    • 2019-12-17
    • 2011-06-04
    相关资源
    最近更新 更多