Swift NSTableview将obj-c转换为swift

时间:2014-10-24 07:08:31

标签: macos cocoa swift

嘿,obj-c中的原始苹果指南就在这里,

https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/TableView/PopulatingView-TablesProgrammatically/PopulatingView-TablesProgrammatically.html#//apple_ref/doc/uid/10000026i-CH14-SW6

例3.2

我一直在完成指南,无法让程序运行,我收到了这些错误:

'AnyObject?' does not have a member named 'identifier'
 line: result.identifier = "HelloWorld"

error: cannot convert the expression's type 'AnyObject?' to type '()'
Line: return result

我做错了什么?

 func tableView(tableView: NSTableView, viewForTableColumn tableColumn: NSTableColumn, row: Int){
    var names: [String] = ["Anna","Alex","brain","jack","gg"]
    var result: AnyObject? = tableView.makeViewWithIdentifier("HelloWorld", owner: self)

    if result == nil
    {
        // Create the new NSTextField with a frame of the {0,0} with the width
        // of the table.
        result = NSTextField(frame: NSRect())
        // set identifier of the NSTextField instance to HelloWorld.
        result.identifier = "HelloWorld"

    }

    result = names[row]
    return result

}

新工作代码

func tableView(tableView: NSTableView, viewForTableColumn tableColumn: NSTableColumn, row: Int) -> NSTextField{


    var names = ["Anna","Alex","Brain","Jack","Hello"]
    var result: NSTextField? = tableView.makeViewWithIdentifier("HelloWorld", owner: self) as? NSTextField        
    if result == nil
    {
        // Create the new NSTextField with a frame of the {0,0} with the width
        // of the table.
        result = NSTextField(frame: NSRect())
        // set identifier of the NSTextField instance to HelloWorld.
        result?.identifier = "HelloWorld"

    }
    result!.bezeled = false
    result?.stringValue = names[row]
    return result!
}

1 个答案:

答案 0 :(得分:1)

这里:

var result: AnyObject? = tableView.makeViewWithIdentifier("HelloWorld", owner: self)

您已将result变量声明为可选的AnyObject - 并且此协议没有identifier属性,而是NSTextField的属性。

您应该做的是使用正确的类型声明该变量:

var result: NSTextField? = tableView.makeViewWithIdentifier("HelloWorld", owner: self) as? NSTextField

由于类型推断也可以缩短:

var result = tableView.makeViewWithIdentifier("HelloWorld", owner: self) as? NSTextField

旁注:我认为你的if正在检查相反的情况:

if result != nil

虽然我认为它应该是:

if result == nil

旁注2

您的函数中没有声明返回值,但您返回NSTextField的实例。 您应该将签名更改为:

func tableView(tableView: NSTableView, viewForTableColumn tableColumn: NSTableColumn, row: Int) -> NSView

并将return语句更改为:

return result!

请注意,result被定义为可选,但是查看方法实现,最后一个非零值可用,所以我使用了强制解包并声明该方法返回非 - 价值。如果你愿意,当然可以随意改变它。