sizeWithAttributes导致“NSString与NSObject不同”

时间:2014-10-25 13:40:10

标签: ios swift

我的代码在iOS 8.0上运行正常,自从我更新到Xcode 6.1 / SDK 8.1后,我无法快速编写代码

我试图从像这样的NSString中获取CGSize

let part1="my text"
let font = UIFont(name: "Arial", size: 30)
var dict = [NSFontAttributeName:font]
let size: CGSize = part1.sizeWithAttributes(dict)

在最后一行我得到错误" NSString与NSObject不相同"

有人可以帮忙吗?

实际上我找到了解决方案,这里是要添加的行以使其工作。

let part1="my text"
let font = UIFont(name: "Arial", size: 30)
if let fontNotNil=font {
    var dict = [NSFontAttributeName:fontNotNil]
    let size: CGSize = part1.sizeWithAttributes(dict)
}

2 个答案:

答案 0 :(得分:0)

尝试以下方法:

let part1: NSString = "my text"

答案 1 :(得分:0)

Optionals都需要正确解开“

let part1: NSString! = "my text"  // For the test since we do not know the type of part1

if let font = UIFont(name: "Arial", size: 30) {
    let dict = [NSFontAttributeName:font] as NSDictionary
    let size: CGSize = part1.sizeWithAttributes(dict)
    println("size: \(size)")
}

输出:

  

尺寸:(96.6796875,33.515625)