0
votes

I'm a swift novice and I hope someone can help.

I want to insert text with a new color and font through a button into the text field (that uses another color and font). Not deleting the original text in the field or change its font or color.

I have managed to insert text thought the button, but no using the NSAttributedString. Don't know if the code in the IBAction will even work, usure where to place the:

let attributedTest = NSAttributedString

    let test = "Testing here"
    let attributes: [NSAttributedString.Key: Any] = [
        .font: UIFont(name:"AvenirNext-Italic", size: 40)!,
        .foregroundColor: UIColor.red,
    ]

    let attributedTest = NSAttributedString(string: test, attributes: attributes as [NSAttributedString.Key : Any])


    @IBAction func justTesting(_ sender: UIButton) {
        noteTextView.text = noteTextView.text! + String(attributedTest)
    }
1

1 Answers

0
votes

You can use this extension to append attributed string

extension NSMutableAttributedString{
    func getAttributedStringByAppending(attributedString:NSMutableAttributedString) -> NSMutableAttributedString{
        let newAttributedString = NSMutableAttributedString()
        newAttributedString.append(self)
        newAttributedString.append(attributedString)
        return newAttributedString
    }
}

@IBAction func justTesting(_ sender: UIButton) {
    let noteTextView = UITextView()
    noteTextView.text = NSMutableAttributedString(string:  noteTextView.text).getAttributedStringByAppending(attributedString: attributedTest)
}