最近同事遇到一個挺變態的需求,雖然後面沒使用這個方法,我還是封裝了下。計算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,末尾的話是非常大的值,採用計算文字大小獲得光標位置。
源碼