0

I am trying to make the selected text in a UITextview bold or italic and this works for me, but let's say I got a string "one two" and I make "one" bold, so it will look like this: "one two". Now if I want to make "two" bold or italic as well this happens: "one two". Is there any explanation why this happens and is there a fix for this?

let main_string = textView2.text
let string_to_change = selectedTextWBU
let range = (main_string! as NSString).range(of: string_to_change)
let attributedString = NSMutableAttributedString(string: main_string!, attributes: [kCTFontAttributeName as NSAttributedStringKey : font])

if selectedTextWBU == ""{

}else{

    //highlight
    if sender.tag == 1{
        print("SELECTEDTEXTWBU ==  \(selectedTextWBU)")
        textView2.attributedText = attributedString

        //italic
    }else if sender.tag == 2{
        attributedString.addAttribute(kCTFontAttributeName as 
            NSAttributedStringKey, value: italicsFont, range: range)          
        textView2.attributedText = attributedString

        //bold
    }else if sender.tag == 3{
        attributedString.addAttribute(kCTFontAttributeName as NSAttributedStringKey, value: boldFont, range: range)
        textView2.attributedText = attributedString

    }

}
Willeke
  • 14,578
  • 4
  • 19
  • 47
  • Instead of using `let main_string = textView2.text`, use `let previousAttrString = textView2.attributedText` and `let attributedString = NSMutableAttributedString(attributedString:previousAttrString)`? – Larme May 06 '18 at 14:52
  • perfect! thanks a lot – user9244481 May 06 '18 at 14:57
  • @Larme Do you also know how to convert a NSAttributedString to an HTML string in swift 4 of course. I have looked everywhere, but I can't find it – user9244481 May 06 '18 at 17:16
  • https://stackoverflow.com/questions/44924139/nsattributedstring-to-html-in-ios-swift-3 ? It's in Swift3, but the only big change should be the `options` param to update with Swift 4 new values (check the doc, they should be look alike) – Larme May 06 '18 at 17:21
  • This does not turn the NSAttributedString into an HTML String right? – user9244481 May 06 '18 at 17:57
  • Yes it does, in Swif3 I said – Larme May 06 '18 at 18:12
  • I got it, thanks again :D – user9244481 May 07 '18 at 16:34

0 Answers0