iOS---获取光标位置caretRectForPosition 可点击textview

1:获取光标位置 目的:textview添加的placeholder和光标居中对齐

CGRect guangBiaoRect = [_wordTV caretRectForPosition:_wordTV.selectedTextRange.start];
    [_wordTV addSubview:_placeHolderL];
    _placeHolderL.sd_layout
    .leftEqualToView(_wordTV).offset(guangBiaoRect.origin.x)
    .topEqualToView(_wordTV).offset(guangBiaoRect.origin.y)
    .autoHeightRatio(0);

2:部分可点击 textview实现部分文本可交互点击
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
// 获取触摸对象
UITouch *touch = [touches anyObject];

// 触摸点
CGPoint point = [touch locationInView:self];
// 通过一个触摸点,查询点击的是不是在下划线对应的文字的frame

// self.selectedRange=NSMakeRange(self.text.length-6, 6);
NSArray *selectionRectArray=[self selectionRectsForRange:self.selectedTextRange];

for (UITextSelectionRect *serRect in selectionRectArray) {
    CGRect strRect=serRect.rect;
    if (CGRectContainsPoint(strRect, point)) {
        if (self.textClick) {
            self.textClick();
        }
        return;
    }
}

}
3:textview文本全部展示masonry
MyTextView *tv=[[MyTextView alloc]init];
tv.font=[UIFont systemFontOfSize:kMainfontSize-4];
tv.backgroundColor=_scrollView.backgroundColor;
_xiYiStr = @"点击“注册”即表示您已经同意协议 《协议》";
tv.editable=NO;
tv.scrollEnabled=NO;
tv.selectable = NO;
tv.layoutManager.allowsNonContiguousLayout = NO;
tv.selectedRange=NSMakeRange(_xiYiStr.length-6, 6);
tv.textClick = ^{
FengLeiXieYiVC *vc=[[FengLeiXieYiVC alloc]init];
[self.navigationController pushViewController:vc animated:YES];

};
[_scrollView addSubview:tv];
[tv mas_makeConstraints:^(MASConstraintMaker *make) {
    make.width.mas_equalTo(loginBtn);
    make.centerX.mas_equalTo(loginBtn);
    make.top.mas_equalTo(loginBtn.mas_bottom).offset(18);
}];

你可能感兴趣的:(iOS---获取光标位置caretRectForPosition 可点击textview)