Posted at

UITextViewで表示中の範囲を取得する方法

More than 5 years have passed since last update.

UITextViewで表示中のテキストの範囲(NSRange)を取得する方法を開示します。


Objective-C

CGPoint startPoint = textView.contentOffset;

UITextPosition *startPosition = [textView closestPositionToPoint:startPoint];
NSInteger location = [textView offsetFromPosition:textView.beginningOfDocument
toPosition:startPosition];
CGPoint endPoint = startPoint;
endPoint.x += textView.frame.size.width;
endPoint.y += textView.frame.size.height;
UITextPosition *endPosition = [textView closestPositionToPoint:endPoint];
NSInteger length = [textView offsetFromPosition:startPosition
toPosition:endPosition];
NSRange range = NSMakeRange(location, length);