UITextView 最后行增加文字自动滚动

UITextView内容添加后,自动滚动到最后一行显示

UITextView 最后行增加文字自动滚动_第1张图片
方法二

方法一

    //1. 连续布局属性 - 关掉
    self.textView.layoutManager.allowsNonContiguousLayout = false 
    //连续布局属性 默认是true的,如果不设置false 每次都会出现一闪一闪的
    //2. 设置textview的可见范围
    self.textView.scrollRectToVisible(CGRectMake(0, mainTextView.contentSize.height - 15, mainTextView.contentSize.width, 10), animated: true)

方法二:

把光标移至最后一个文字 比方法一精确,无需设置可见范围

    //1.
    self.textView.layoutManager.allowsNonContiguousLayout = false
    //2
    let allStrCount = textView.text.characters.count //获取总文字个数
    textView.scrollRangeToVisible(NSMakeRange(0, allStrCount))//把光标位置移到最后
    //使用可放在你的自定义方法或者UITextViewDelegate方法里面使用,比如文本变更时候 - textViewDidChange

改变textView的文字间距

    let paragraphStyle = NSMutableParagraphStyle()
    paragraphStyle.lineSpacing = 6
    let attributes = [NSFontAttributeName: UIFont.systemFontOfSize(14),NSParagraphStyleAttributeName: paragraphStyle]
    textView.attributedText = NSAttributedString(string: textView.text, attributes: attributes)

你可能感兴趣的:(UITextView 最后行增加文字自动滚动)