【问题标题】:NSAttributedString issues in SwiftSwift 中的 NSAttributedString 问题
【发布时间】:2015-02-05 04:08:42
【问题描述】:

无论我走哪条路,我都遇到了 NSAtributedString 的问题,而且似乎无法弄清楚问题是什么。

使用下面的代码,我得到:Cannot invoke 'init' with an argument list of type '(string: StringLiteralConvertible, attributes: $T6)'

let cancelButtonTitle = NSAttributedString(string: "CANCEL", attributes: [NSFontAttributeName: buttonFont, NSForegroundColorAttributeName: UIColor.whiteColor()])

有什么想法吗?我在 xcode 6.1 和 6.2 中尝试过。

【问题讨论】:

标签: ios iphone swift xcode6 nsattributedstring


【解决方案1】:

NSFontAttributeName 应设置为 UIFont 对象。

let buttonFont = UIFont.systemFontOfSize(10)

let cancelButtonTitle = NSAttributedString(string: "CANCEL",
    attributes: [NSFontAttributeName: buttonFont,
        NSForegroundColorAttributeName: UIColor.whiteColor()])

或者如果您使用的是特定字体。

if let buttonFont = UIFont(name: "Your Font", size: 10) {

    let cancelButtonTitle = NSAttributedString(string: "CANCEL",
    attributes: [NSFontAttributeName: buttonFont,
        NSForegroundColorAttributeName: UIColor.whiteColor()])
}

因为UIFont(name:,size:)构造函数返回一个optional,所以在NSAttributedString中使用之前需要先解包

【讨论】:

  • 我使用的是特定字体:let buttonFont = UIFont(name: "AvenirNext-Bold", size: 25) 所以修复了它。
猜你喜欢
  • 1970-01-01
  • 2011-11-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-12-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多