textview 富文本 更改textview的字间距

75 阅读1分钟

extension AICreatDetailViewController:UITextViewDelegate {

    func  textViewDidChange(_ textView:  UITextView ) {

        self.topPlaceholdLabel.isHidden = textView.text.count != 0

        if let selectedRange = textView.markedTextRange  {

            let newtext = textView.text(in: selectedRange)

            if newtext?.count ?? 0 > 0 {

                return

            }

        }  //用来解决不能输入中文

        let loc = textView.selectedRange.location //用来定位光标

        let len = textView.selectedRange.length  //用来定位光标

    

        //获取文本内容

        let  str = textView.text!

        if str.count > 500 {

            textView.text = (str as NSString).substring(to: 500)

        }

   

        

        textView.attributedText =  attrWithString(content: textView.text)

  

        textView.selectedRange = NSMakeRange(loc, len)   //用来定位光标

        textView.scrollRangeToVisible(textView.selectedRange)

    }

    func attrWithString(content:String) -> NSMutableAttributedString {

        let attributes = NSMutableAttributedString(string: content)

        attributes.addAttribute(.font, value: UIFont.systemFont(ofSize: 14, weight: .medium), range: NSRange(location: 0, length: content.count))

        let paragraphStyle = NSMutableParagraphStyle()

        paragraphStyle.lineSpacing = 5 // 段落高度

        paragraphStyle.alignment = .left

        paragraphStyle.lineBreakMode = .byCharWrapping

        attributes.addAttribute(.paragraphStyle, value: paragraphStyle, range: NSRange(location: 0, length: content.count))

        attributes.addAttribute(.foregroundColor, value: UIColor.white, range: NSRange(location: 0, length: content.count))

        return attributes

    }

}