5

这是我在 UITextView 中的内容...

==>“‘大都会’用餐体验,提供注重视觉细节和品味的精致美食。”

现在我的问题很简单,如何在文本视图中找到“体验”一词的位置(x,y)。

任何解决方案将不胜感激。

4

3 回答 3

3

试试这个:

- (CGPoint)getPoint:(UITextView *)textView
{
    NSRange range = [textView.text rangeOfString:@"experience"];

    UITextPosition *beginning = textView.beginningOfDocument;
    UITextPosition *start = [textView positionFromPosition:beginning offset:range.location];
    UITextPosition *end = [textView positionFromPosition:start offset:range.length];
    UITextRange *textRange = [textView textRangeFromPosition:start toPosition:end];
    CGRect rect = [textView firstRectForRange:textRange];
    return rect.origin;
}
于 2015-10-10T05:07:09.577 回答
3

如果你想在 Swift 中试试这个

    let range: NSRange = (txtView.text as NSString).range(of: text)
    let beginning: UITextPosition? = txtView.beginningOfDocument
    let start: UITextPosition? = txtView.position(from: beginning!, offset: range.location)
    let end: UITextPosition? = txtView.position(from: start!, offset: range.length)
    let textRange: UITextRange? = txtView.textRange(from: start!, to: end!)
    let rect: CGRect = txtView.firstRect(for: textRange!)
于 2018-06-22T11:03:57.003 回答
2

使用 sizeWithFont,它应该是这样的:

NSString *text = textView.text;
NSString *substring = [text substringToIndex:[text rangeOfString:@"experience"].location];
CGSize size = [substring sizeWithFont:textView.font];
CGPoint p = CGPointMake((int)size.width % (int)textView.frame.size.width, ((int)size.width / (int)textView.frame.size.width) * size.height);
于 2013-01-17T10:04:20.807 回答