Swift文本的中心和粗体部分

bla*_*011 2 ios swift2

我想以我的段落的标题为中心并加粗.到目前为止,我可以使标题大胆,但我不能把它放在中心位置.

这是我的代码:

    let title = "Title of Paragraph"

    let attrs = [NSFontAttributeName : UIFont.boldSystemFontOfSize(15)]

    let boldString = NSMutableAttributedString(string:title, attributes:attrs)

    let normalText = "Something here.............."

    let attributedString = NSMutableAttributedString(string:normalText)

    boldString.appendAttributedString(attributedString)

    label.attributedText = boldString
Run Code Online (Sandbox Code Playgroud)

我试图在attrs中添加另一个属性:

    let attrs = [NSFontAttributeName : UIFont.boldSystemFontOfSize(15), NSTextAlignment: NSTextAlignment.Center]
Run Code Online (Sandbox Code Playgroud)

我不确定这是否是以它为中心的正确方法,但它仍然会给出错误"表达类型不明确而没有更多上下文"

我搜索了错误,但似乎我仍然无法解决问题

Rap*_*ira 7

我认为问题NSTextAlignment在于您要在字典上添加的密钥.它的类型Int与前一个键变得模糊不清,String所以我猜这就是编译器抱怨的原因.无论哪种方式NSTextAlignment都不是在NSMutableAttributedString属性初始化器上使用的有效密钥.

也许你正在寻找类似的东西:

let string = "Any String"
let style = NSMutableParagraphStyle()
style.alignment = .Center

let attributes = [
    NSFontAttributeName: UIFont.boldSystemFontOfSize(15),
    NSParagraphStyleAttributeName: style
]

let attributedString = NSMutableAttributedString(string: string, attributes: attributes)
Run Code Online (Sandbox Code Playgroud)