Swift 3 - 更改UITextView所选文本的字体

时间:2017-03-20 08:48:05

标签: swift textview nsmutableattributedstring

我尝试在textview的选定范围内应用格式。问题是当应用所选文本格式时,其余文本将重置其格式。

这是我的代码:

 if let text = textView.text {  

    if let textRange = textView.selectedTextRange {

          if let selectedText = textView.text(in: textRange) {

                let range = (text as NSString).range(of: selectedText)

                let attributedString = NSMutableAttributedString(string:text)
                attributedString.addAttribute(NSFontAttributeName, value: UIFont.systemFont(ofSize: 18) , range: range)

                self.textView.attributedText = attributedString
            }
        }
    }

1 个答案:

答案 0 :(得分:1)

  let range = textView.selectedRange
  let string = NSMutableAttributedString(attributedString: 
  textView.attributedText)
  let attributes = [NSForegroundColorAttributeName: UIColor.redColor()]
   string.addAttributes(attributes, range: textView.selectedRange)
  textView.attributedText = string
  textView.selectedRange = range
相关问题