UITextView自定义文字属性后光标老是自动跳到末尾的问题

来源:互联网 发布:云杉网络融资 编辑:程序博客网 时间:2024/05/01 21:17

在使用textView控件中,我们经常需要自定义文字的大小、行间距等属性,让用户输入文字时可以自动按照预先设置好的文字属性显示,但是直接在storyboard中设置是无效的,在网上查到的OC中的方法基本上是这样:

-(void)textViewDidChange:(UITextView *)textView{    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];    paragraphStyle.lineSpacing = 3;    NSDictionary *attributes = @{                                 NSFontAttributeName:[UIFont systemFontOfSize:15],                                 NSParagraphStyleAttributeName:paragraphStyle                                 };    textView.attributedText = [[NSAttributedString alloc] initWithString:textView.text attributes:attributes];}


在swift中,同样可以实现textView的delegate,在textViewDidChange方法中加入如下代码:

func textViewDidChange(textView: UITextView) {        var paragraphyStyle = NSMutableParagraphStyle()        //行间距        paragraphyStyle.lineSpacing = 3        //对齐方式设置为左右对齐        paragraphyStyle.alignment = NSTextAlignment.Justified        var attributes = NSDictionary()        attributes = [NSFontAttributeName: UIFont.systemFontOfSize(15),NSParagraphStyleAttributeName: paragraphyStyle]        //自定义文字属性        textView.attributedText = NSAttributedString(string: textView.text, attributes: attributes as [NSObject : AnyObject])}

但是只实现以上代码之后,我发现我的textView出现了一个奇怪的问题:如果在已经存在的文字中间添加文字,每次输入之后光标都会提动跳到末尾去,不知道是我其他地方写的有问题还是这个代理遗漏了什么(希望知道原因的朋友可以为我解答一下),不过我加了两行代码来控制光标的位置,完美解决了这个问题,分享给同样遇到这个问题的朋友,代码如下:

func textViewDidChange(textView: UITextView) {        <span style="color:#ff0000;">//保存光标的当前位置        let loc = textView.selectedRange.location</span>        var paragraphyStyle = NSMutableParagraphStyle()        //行间距        paragraphyStyle.lineSpacing = 3        //对齐方式设置为左右对齐        paragraphyStyle.alignment = NSTextAlignment.Justified        var attributes = NSDictionary()        attributes = [NSFontAttributeName: UIFont.systemFontOfSize(15),NSParagraphStyleAttributeName: paragraphyStyle]        //自定义文字属性        textView.attributedText = NSAttributedString(string: textView.text, attributes: attributes as [NSObject : AnyObject])        <span style="color:#ff0000;">//让光标位置保持不变        textView.selectedRange = NSRange(location: loc,length: 0)</span>}

在设置字体属性之前先保存一下当前光标所在的位置,在最后把这个位置再重新给回textView.selectedRange,这样如果不是在末尾输入文字而是在中间某处输入的话,光标也会在当前编辑的位置闪烁,而不会跳到末尾去。





0 0
原创粉丝点击