2017-03-20 8 views
0

私はtextviewの選択範囲に書式を適用しようとしています。問題は、選択されたテキスト形式が適用され、残りのテキストがその形式をリセットしたときです。ここで Swift 3 - UITextViewの選択したテキストのフォントを変更します。

は私のコードです:

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 
      } 
     } 
    } 
+0

のは明確にしましょう: '(NS)STRING'は、それはそれは理論的にはありますなどのフォント、色、の知識を持っていない、文字だけのチェーンです'UILabel'、' UITextView'など、それを行うUIのものです。 'NSAttributedString'は、古典的な" String "にこれらの情報を追加して、UIStuffのレンダリングを異なるようにすることができます。ですから、 'let attributedString = NSMutableAttributedString(string:text)'を実行すると '(NS)String'である' text'を使い、以前の内容をすべて失いました。 – Larme

+0

代わりに、擬似コードではSwiftを使用しません: 'NSMutableAttributedString attributedString = self.textView.attributedText.mutableCopy'、次に' attributedString.addAttribute(NSFontAttributeName、value:UIFont.systemFont(ofSize:18)、range:range) '、次に' self.textView.attributedText = attributedString' – Larme

+0

@Larmeありがとう – NST

答えて

0
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 
関連する問題