Swift文本的中心和粗体部分

时间:2016-01-21 03:53:18

标签: 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

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

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

我不确定这是否是正确的中心方式,但它仍会出现错误"表达类型不明确且没有更多上下文"

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

2 个答案:

答案 0 :(得分: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)

答案 1 :(得分:1)

在UILabel上尝试一个类别:

<强>的UILabel + boldText

func boldSubstring(substring: String) {

   var range: NSRange = self.text!.rangeOfString(substring)
   var attributedText: NSMutableAttributedString = NSMutableAttributedString(attributedString: self.attributedText)
   attributedText.setAttributes([NSFontAttributeName: UIFont.boldSystemFontOfSize(self.font.pointSize)], range: range)
   self.attributedText = attributedText

}

func centerAlginement(substring:String) {

   var paragraphStyle: NSMutableParagraphStyle = NSMutableParagraphStyle.new
   paragraphStyle.alignment = .Center
   var attributedString: NSAttributedString = NSAttributedString.alloc(string: substring, attributes:  [NSParagraphStyleAttributeName: paragraphStyle])
   self.attributedText = attributedString

}

现在您可以在视图导入类别类中将其用于视图

myLabel.text = "DemoText"
myLabel.boldSubstring(myLabel.text)
myLabel.centerAlginement(myLabel.text)