1、UITextView创建初始化,设置相关属性,添加需要的方法
2、设置插入Insert和覆盖Replace的转换按钮
相关代码:
-(void)btnDown:(UIButton *)btn{
if (_isInsert==YES) {
_isInsert=NO;
[navBtn setTitle:@"Replace"forState:UIControlStateNormal];
}else{
_isInsert=YES;
[navBtn setTitle:@"Insert"forState:UIControlStateNormal];
}
}
3、用BooL值做判断是插入Insert还是覆盖Replace,当是插入Insert时不做任何处理(本身输入就是酱紫的),当是覆盖Replace时,在下边的方法中做对应处理
相关代码:
- (void)textViewDidChange:(UITextView *)textView {
if (_isInsert==NO) {
NSRange range;
range.location=_mainTextView.selectedRange.location;
range.length=1;
NSString *changeText=[NSStringstringWithFormat:@"%@",_mainTextView.text];
NSString *tailStr=[changeTextsubstringFromIndex:range.location];
if (tailStr.length==0) {
return;
}else{
changeText=[changeText stringByReplacingCharactersInRange:range withString:@""];
_mainTextView.text=changeText;
}
range.location=range.location;
range.length=0;
_mainTextView.selectedRange=range;
}
}
为了有区分效果:
UIImageView *_flashingCursor;
4.2创建初始化_flashingCursor,设置相关属性,调用闪烁方法,起初为插入Insert时将其隐藏Replace
[_flashingCursor.layeraddAnimation:[CABasicAnimationopacityForever_Animation:0.5]forKey:nil];
闪烁效果的demo(GitHub上面的)
在两个方法中做相关操作
- (void)textViewDidChangeSelection:(UITextView *)textView{
_flashingCursor.frame=CGRectMake([textViewcaretRectForPosition:textView.selectedTextRange.start].origin.x, [textView caretRectForPosition:textView.selectedTextRange.start].origin.y,_flashingCursor.frame.size.width,_flashingCursor.frame.size.height);
}
- (BOOL)textViewShouldBeginEditing:(UITextView *)textView{
if (_isInsert==NO) {
_flashingCursor.frame=CGRectMake([textViewcaretRectForPosition:textView.selectedTextRange.start].origin.x, [textView caretRectForPosition:textView.selectedTextRange.start].origin.y,_flashingCursor.frame.size.width,_flashingCursor.frame.size.height);
_flashingCursor.hidden=NO;
}else{
_flashingCursor.hidden=YES;
}
}