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

时间:2016-04-15 06:27:47

标签: ios string swift uilabel nsmutablestring

我希望修改单个UILabel文本,如下所示。

enter image description here

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

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

4 个答案:

答案 0 :(得分:1)

请参阅此示例,添加相应的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

答案 1 :(得分:1)

您可以使用属性字符串:

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

答案 2 :(得分:1)

我修改了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

    }

答案 3 :(得分:0)

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