Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
476 views
in Technique[技术] by (71.8m points)

iphone - Get X and Y coordinates of a word in UITextView

I asked a developer (TwoLivesLeft, the creators of Codea) how they did syntax highlighting in their app. He replied :

@TD2 the Codea editor is implemented using a UITextView. The highlighting is done by overlaying subviews in the appropriate positions — usually UILabels. They are dequeued from a re-use pool, similar to the way UITableViewCells work. During scrolling, the lines requiring re-highlighting pull markers out of the pool and lines that have moved off screen dump their markers back into the pool.

Can anyone explain how I would get the x and y of a certain word?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

UITextView conforms to UITextInput, of which a detailed description can be found here.

Take a look at the required methods "textRangeFromPosition:toPosition:", "positionFromPosition:offset:", "positionFromPosition:inDirection:offset:", and some of the other geometric-based methods in the UITextInput Protocol. Those might provide the functionality you are looking for.

I have not actually tried to make sure these work the way you want them too, but that looks like its about what you need.

Let me know if you need any more help!


UPDATE:

Here is some sample code of how to do this. I ended up getting the "firstRectForRange:" method to work. This code basically takes the last three letters of the UITextView "textStuff" and highlights it green.

UITextView *textStuff = [[UITextView alloc] init];
textStuff.frame = CGRectMake(2.0, 200.0, 200.0, 40.0);
textStuff.text = @"how are you today?";
textStuff.textColor = [UIColor blackColor];

UITextPosition *Pos2 = [textStuff positionFromPosition: textStuff.endOfDocument offset: nil];
UITextPosition *Pos1 = [textStuff positionFromPosition: textStuff.endOfDocument offset: -3];

UITextRange *range = [textStuff textRangeFromPosition:Pos1 toPosition:Pos2];

CGRect result1 = [textStuff firstRectForRange:(UITextRange *)range ];

NSLog(@"%f, %f", result1.origin.x, result1.origin.y);

UIView *view1 = [[UIView alloc] initWithFrame:result1];
view1.backgroundColor = [UIColor colorWithRed:0.2f green:0.5f blue:0.2f alpha:0.4f];
[textStuff addSubview:view1];

Result of running this code:

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...