Master Stroke
Master Stroke

Reputation: 5128

Finding (x,y) coordinate of specified word in UITextView

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.

Upvotes: 5

Views: 2702

Answers (3)

Pushp
Pushp

Reputation: 1060

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!)

Upvotes: 3

Hsm
Hsm

Reputation: 1540

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

Upvotes: 3

shem
shem

Reputation: 4712

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);

Upvotes: 2

Related Questions