嘿,obj-c 中的原始苹果指南就在这里,
示例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!
}
最佳答案
这里:
var result: AnyObject? = tableView.makeViewWithIdentifier("HelloWorld", owner: self)
您已将 result
变量声明为可选的 AnyObject - 并且此协议(protocol)没有 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 result!
请注意,result
被定义为可选,但查看方法实现,最后有一个非零值可用,因此我使用了强制展开并声明该方法返回一个非可选值。当然,如果您愿意,可以随意更改。
关于macos - Swift NSTableview 将 obj-c 转换为 swift,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26543086/