views:

27

answers:

1

Hi, I am trying to calculate the closest text position in a string (text of UITextView) from a CGPoint. I wonder if some methods in NSString are useful for this? I would appreciate a good explanation of the following methods. Because I think they are useful here. I read the docs but I don't really understand what they do ;(

NSString instance methods:
– getLineStart:end:contentsEnd:forRange:
– lineRangeForRange:
– getParagraphStart:end:contentsEnd:forRange:
– paragraphRangeForRange:

Thanks in advance

A: 

I think you'll find this link helpful:

http://developer.apple.com/iphone/library/documentation/uikit/reference/NSString_UIKit_Additions/Reference/Reference.html

It shows you how to calculate the total size (in points) of a string, rendered at a specific font & size. You can then slice up your string into quadrants (or segments) and get a decent index in the string where the CGPoint is.

For example, if you calculate the width & height of the entire string, you'd be able to tell which 1/2 of the string the CGPoint lies in. You can further slice up the string into more quadrants and narrow it in.

The methods you refer to are useful if you know the index positions of the sub-string start/end you want, but you aren't sure how it is being wrapped. They might be useful in this scenario, but I'm not sure.

Ben Scheirman