UITextField中的UITextPosition
有什么办法让我通过文本字段的UITextRange对象获得UITextField的当前插入符号位置? UITextField即使有任何用途也会返回UITextRange? UITextPosition的公共接口没有任何可见的成员。UITextField中的UITextPosition
昨晚我正面临同样的问题。事实证明,您必须使用UITextField上的offsetFromPosition来获取所选范围的“开始”的相对位置来计算出位置。
例如
// Get the selected text range
UITextRange *selectedRange = [self selectedTextRange];
//Calculate the existing position, relative to the beginning of the field
int pos = [self offsetFromPosition:self.beginningOfDocument
toPosition:selectedRange.start];
我结束了使用endOfDocument,因为更改文本字段后更容易恢复用户的位置。我写了,这里一个博客文章:
http://neofight.wordpress.com/2012/04/01/finding-the-cursor-position-in-a-uitextfield/
我用的UITextField类别和实施setSelectedRange和的selectedRange(就像在UITextView中类实现的方法)。在B2Cloud here上找到一个示例,其代码如下:
@interface UITextField (Selection)
- (NSRange) selectedRange;
- (void) setSelectedRange:(NSRange) range;
@end
@implementation UITextField (Selection)
- (NSRange) selectedRange
{
UITextPosition* beginning = self.beginningOfDocument;
UITextRange* selectedRange = self.selectedTextRange;
UITextPosition* selectionStart = selectedRange.start;
UITextPosition* selectionEnd = selectedRange.end;
const NSInteger location = [self offsetFromPosition:beginning toPosition:selectionStart];
const NSInteger length = [self offsetFromPosition:selectionStart toPosition:selectionEnd];
return NSMakeRange(location, length);
}
- (void) setSelectedRange:(NSRange) range
{
UITextPosition* beginning = self.beginningOfDocument;
UITextPosition* startPosition = [self positionFromPosition:beginning offset:range.location];
UITextPosition* endPosition = [self positionFromPosition:beginning offset:range.location + range.length];
UITextRange* selectionRange = [self textRangeFromPosition:startPosition toPosition:endPosition];
[self setSelectedTextRange:selectionRange];
}
@end
谢谢。你的代码确实帮助我弄清楚了如何在'UITextView'中使用'UITextPosition'。 – derpoliuk 2017-12-22 07:58:33
您的链接指向可疑恶意软件站点。请查看 – 2015-08-29 11:17:29