Search code examples
swiftstringstring-interpolation

Attributed String with String interpolation does not work(swift)


I want to use an attributed string in string interpolation. but it works as it appears in the screenshot. the attributed string is not formatted the right way. why does this happen? Is there an alternative way to overcome this problem?

enter image description here

@IBOutlet weak var denemeLabel: UILabel!

    override func viewDidLoad() {
        super.viewDidLoad()


        var nameString: String = "any String"
            denemeLabel.text = ""

            let nameAttribute = [NSAttributedString.Key.font: UIFont(name: "Chalkduster", size: 18)]
            let attributedNameString = NSMutableAttributedString(string: nameString, attributes: nameAttribute)

            let nsAttributedString =  NSMutableAttributedString(string:"\(attributedNameString) another String")
            denemeLabel.attributedText = nsAttributedString

    }

Solution

  • Xcode 10.1 Swift 4.2

    var nameString: String = "any String"
    
    // Set Attributes for the first part of your string
    let att1 = [NSAttributedString.Key.font : UIFont(name: "Chalkduster", size: 18.0)]
    
    // Set Attributes for the second part of your string
    let att2 = [NSAttributedString.Key.font : UIFont.systemFont(ofSize: 18)]
    
    // Create the first part of your attributed string
    let attributedString1 = NSMutableAttributedString(string: nameString, attributes: att1)
    
    // Create the second part of your attributed string
    let attributedString2 = NSMutableAttributedString(string: "another String", attributes: att2)
    
    // Append the second string to the end of the first string
    attributedString1.append(attributedString2)
    
    // Update your label
    denemeLabel.attributedText = attributedString1
    

    enter image description here