5

Here is my contents in UITextView...

==>"A ‘Metropolitan’ dining experience offering exquisite food prepared with attention to visual detail & taste."

Now my question is simple and short,how to find the location(x,y) of a word "experience" within the textview.

Any solution will be greatly appreciated.

Master Stroke
  • 5,108
  • 2
  • 26
  • 57
  • Similar to this http://stackoverflow.com/questions/8683848/how-can-i-get-the-selected-text-frame-from-a-uitextview Hope its a same as what you wanted ! – Reefaq Jan 17 '13 at 10:20
  • @Reefaq..thanks rafeeq,but the solution is hardcoded..i am sure with the use some calculation logic we can achieve it. – Master Stroke Jan 17 '13 at 10:27
  • 2
    play with the codes then you can achieve it .. you can take that link as a direction to get your solution. – Reefaq Jan 17 '13 at 10:47

3 Answers3

3

Try this:

- (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;
}
Hsm
  • 1,510
  • 17
  • 16
3

Try this if you want in 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!)
Pushp
  • 1,064
  • 10
  • 18
2

use sizeWithFont, it suppose to be something like this:

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);
shem
  • 4,686
  • 2
  • 32
  • 43