Search code examples
iosswiftfontsuikitnsattributedstring

How do I append two attributed strings with different fonts?


Here I have tried to append two attributed strings in a single UILabel but I made some mistake so any one can find my mistake please?

let textFontAttributes = [
            NSFontAttributeName : font,
            // Note: SKColor.whiteColor().CGColor breaks this
            NSForegroundColorAttributeName: UIColor.whiteColor(),
            NSStrokeColorAttributeName: UIColor.blackColor(),
            // Note: Use negative value here if you want foreground color to show
            NSStrokeWidthAttributeName: -8]

Solution

  • This is the demo, you can have a try, In fact, you should provide more info of what the wrong is or what the error is.

    var firstString  = "Hello" as NSString
    
    var secondString = " World"  as NSString
    
    var totalString = firstString.stringByAppendingString(secondString as String) as NSString
    
    let firsttAttributes = [
        NSFontAttributeName : UIFont.systemFontOfSize(16),
        // Note: SKColor.whiteColor().CGColor breaks this
        NSForegroundColorAttributeName: UIColor.whiteColor(),
        NSStrokeColorAttributeName: UIColor.blackColor(),
        // Note: Use negative value here if you want foreground color to show
        NSStrokeWidthAttributeName: -8]
    
    let secondAttributes = [
        NSFontAttributeName : UIFont.systemFontOfSize(12),
        // Note: SKColor.whiteColor().CGColor breaks this
        NSForegroundColorAttributeName: UIColor.redColor(),
        NSStrokeColorAttributeName: UIColor.blackColor(),
        // Note: Use negative value here if you want foreground color to show
        NSStrokeWidthAttributeName: -8]
    
    var attributedString = NSMutableAttributedString(string: totalString as String, attributes: firsttAttributes)
    
    var secondRange = totalString.rangeOfString(secondString as String)
    
    if secondRange.location != NSNotFound {
        attributedString.addAttributes(secondAttributes, range: secondRange)
    }