这是我在UITextView中的内容......
==>"'大都会'用餐体验,提供精致的食物,注重视觉细节和。味道"
现在我的问题很简单,如何找到单词的位置(x,y)"体验"在textview中。
任何解决方案都将不胜感激。
答案 0 :(得分: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);
答案 1 :(得分:2)
试试这个:
- (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;
}
答案 2 :(得分:0)
如果要在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!)