如何在单个 UILabel 文本上获取两个普通字符串和 NSMutableString?

How to get two a normal string and NSMutableString on a single UILabel Text?

我想要一个 UILabel 文本进行如下修改。

如何使用 NSMutableString 或 UILabel 的 attributedText 属性 来完成它?感谢帮助。

注意:名称 'John Doe' 是从 API 派生的用户帐户名。

参考这个例子,添加你合适的Attribute.

let text = NSMutableAttributedString(string: "Welcome John Doe")
text.addAttribute(NSFontAttributeName, value: UIFont(name: "YourFont", size: 18)!, range: NSMakeRange(8, text.characters.count - 8))
label.attributedText = text

您可以使用属性字符串:

let text = "Welcome John Doe"
let textWithColor = "John Doe"
let range = text.rangeOfString(textWithColor)

let attributedString = NSMutableAttributedString(string:text)
attributedString.addAttribute(NSForegroundColorAttributeName, value: UIColor.orangeColor() , range: range)

label.attributedText = attributedString

我修改了 Ronit 的答案并在下面分享。

var userNameString:String?

    override func viewWillAppear(animated: Bool) {

        self.makeAttributedUserNameTitleLabelText()
    }
    func makeAttributedUserNameTitleLabelText()
    {
        userNameString = "John Doe"
        let text = "Welcome  "+userNameString!
        let range =  NSMakeRange(8, text.characters.count - 8)
        let attributedString = NSMutableAttributedString(string:text)
        attributedString.addAttribute(NSForegroundColorAttributeName, value: UIColor.orangeColor(), range: range)
        attributedString.addAttribute(NSFontAttributeName, value: UIFont(name: "Roboto-Bold", size: 14)!, range: range)
        self.userNameTitleLabel.attributedText = attributedString

    }
info.name = "John Doe" //which come from api

let nameValue = "Welcome " + "\(info.name!)" 

let bSerString = "\(info.name!)" 

let nameAttribt = NSMutableAttributedString(string: nameValue)
let bSRange = nameValue.rangeOfString(bSerString as String)

nameAttribt.addAttribute(NSFontAttributeName, value: UIFont(name: "OpenSans-Semibold", size: 14)!, range: bSRange)

nameAttribt.addAttribute(NSForegroundColorAttributeName, value: UIColor.orangeColor(), range: bSRange)

self.lblName.attributedText = nameAttribt