Can't get attributed string to work in Swift

强颜欢笑 提交于 2019-12-24 03:16:57

问题


I'm trying to set some attributes of a string in code, but can't get NSAttributedString to work. This is the function, that's supposed to change the string:

func getAttributedString(string: String) -> NSAttributedString
{
    var attrString = NSMutableAttributedString(string: string)
    var attrs = [NSFontAttributeName : UIFont.boldSystemFontOfSize(18.0)]

    attrString.setAttributes(attrs, range: NSMakeRange(0, attrString.length))

    return attrString
}

And this is how I use it:

if (self.product.packageDimensions != nil) {
        self.descriptionLabel.text = 
                   self.descriptionLabel.text + self.getAttributedString("Package dimensions:").string + 
                   "\n\(self.product.packageDimensions) \n"
    }

But the font stays the same. What am I doing wrong ?


回答1:


You make 2 errors in your code.

  1. setAttributes needs a Dictionary, not an Array
  2. when you use the string attribute, you will only get a String, all attributes are lost.

To add or change attributes to a attributedString it has to be mutable. You only get a NSMutableString from the attributedText attribute. If you want to change it create a mutable version from it and change it. Then you may set the attributedText to the new mutable version.


If you can give the attributed string as an argument, I will give you an example that works:

func setFontFor(attrString: NSAttributedString) -> NSMutableAttributedString {
    var mutableAttrString: NSMutableAttributedString = NSMutableAttributedString(attributedString: attrString)
    let headerStart: Int = 0
    let headerEnd: Int = 13
    mutableAttrString.addAttribute(NSFontAttributeName, value: UIFont.boldSystemFontOfSize(18.0), range: NSMakeRange(headerStart, headerEnd))

    return mutableAttrString
}

Usage:

myLabel.attributedText = setFontFor(myLabel.attributedText)

As you can see I used the attributedText property of the UILabel class, it also works for UITextView and others. If you have another label, you can create a new NSAttributedString with the initializer NSAttributedString(normalString) as you already used in the question code.




回答2:


if (self.product.packageDimensions != nil) {
        self.descriptionLabel.attributedText = 
                   self.descriptionLabel.attributedText + self.getAttributedString("Package dimensions:").string + 
                   "\n\(self.product.packageDimensions) \n"
    }

You should use the attributedText method



来源:https://stackoverflow.com/questions/25199580/cant-get-attributed-string-to-work-in-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!