最近同事遇到一个挺变态的需求,虽然后面没使用这个方法,我还是封装了下。计算textField的光标偏移量。估计用到的不多,图一乐吧。
- (CGFloat)cursorOffset
{
NSArray *textrect = [self selectionRectsForRange:[self selectedTextRange]];
CGRect rect = ((UITextSelectionRect *)textrect[0]).rect;
if (rect.origin.x > 100000) {
CGSize size = [self boundingRectWithSize:CGSizeMake(0, CGRectGetHeight(self.frame))];
if (self.textAlignment == NSTextAlignmentCenter){
CGSize size = [self boundingRectWithSize:CGSizeMake(0, CGRectGetHeight(self.frame))];
CGFloat width = CGRectGetWidth(self.frame);
return width - (width - size.width)/2.0f;
} else if (self.textAlignment == NSTextAlignmentRight){
return CGRectGetWidth(self.frame);
} else {
return size.width;
}
}
return rect.origin.x;
}
核心代码如下:
NSArray *textrect = [self selectionRectsForRange:[self selectedTextRange]];
CGRect rect = ((UITextSelectionRect *)textrect[0]).rect;
通过获得选择的范围获得相应的rect,末尾的话是非常大的值,采用计算文字大小获得光标位置。
源码