无法在 Swift 中使用属性字符串 [英] Can't get attributed string to work in Swift

查看:32
本文介绍了无法在 Swift 中使用属性字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在代码中设置字符串的某些属性,但无法让 NSAttributedString 工作.这是应该改变字符串的函数:

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 ?

推荐答案

您在代码中犯了 2 个错误.

You make 2 errors in your code.

  1. setAttributes 需要一个 Dictionary,而不是一个 Array
  2. 当你使用string属性时,你只会得到一个String,所有的属性都丢失了.
  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.

<小时>

要向attributedString 添加或更改属性,它必须可变.您只能从 attributedText 属性中获得一个 NSMutableString.如果你想改变它,从它创建一个可变版本并改变它.然后您可以将属性文本设置为新的可变版本.


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
}

用法:

myLabel.attributedText = setFontFor(myLabel.attributedText)

如您所见,我使用了 UILabel 类的 attributedText 属性,它也适用于 UITextView 等.如果你有另一个标签,你可以用你在问题代码中已经使用的初始化器 NSAttributedString(normalString) 创建一个新的 NSAttributedString.

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.

这篇关于无法在 Swift 中使用属性字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆