gpt4 book ai didi

macos - Swift NSTableview 将 obj-c 转换为 swift

转载 作者:行者123 更新时间:2023-11-30 10:21:06 25 4
gpt4 key购买 nike

嘿,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!
}

最佳答案

这里:

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com