我正在尝试将数据从我的popover传递回另一个启动它的类。我读到这样做的模式是使用委托,所以我这样做了:
/*MyMainClass.swift*/
class MyMainClass: UserInfoPopoverDelegate {
var popover: NSPopover = NSPopover()
func showAskForUserInfoPopup() {
if let button = statusItem.button {
if !popover.isShown {
popover.delegate = self //error here
popover.contentViewController = UserInfoPopupController(nibName: "UserInfoPopup", bundle: nil)
popover.show(relativeTo: button.bounds, of: button, preferredEdge: NSRectEdge.minY)
}
}
}
func submitAndClose(str: String){
print(str)
popover.performClose(nil)
}
}
然后我有一个带有控制器的xib:
class UserInfoPopupController: NSViewController {
@IBOutlet weak var phoneField: NSTextField!
@IBOutlet weak var emailField: NSTextField!
weak var delegate: UserInfoPopoverDelegate?
override func viewDidLoad() {
super.viewDidLoad()
}
@IBAction func close(_ sender: Any) {
delegate?.submitAndClose(str: "close pressed")
}
@IBAction func submitDetails(_ sender: Any) {
delegate?.submitAndClose(str: "submit pressed")
}
}
protocol UserInfoPopoverDelegate: class {
func submitAndClose(str: String)
}
问题发生在我在代码中留下评论的位置,并且是Cannot assign value of type 'MyMainClass' to type 'NSPopoverDelegate'
。如果我的主要课程标题为class MyMainClass: NSPopoverDevelegate
,它会抱怨我没有实现NSObjectProtocol
我不想做的所有方法。
答案 0 :(得分:1)
这一切都非常混乱。您在UserInfoPopupController上创建了一个delegate
属性,但您正在为NSPopover
分配一个委托。因此,您需要将代码更改为以下内容:
func showAskForUserInfoPopup() {
if let button = statusItem.button {
if !popover.isShown {
let contentViewController = UserInfoPopupController(nibName: "UserInfoPopup", bundle: nil)
contentViewController.delegate = self //This is where you should be assigning the delegate
popover.contentViewController = contentViewController
popover.show(relativeTo: button.bounds, of: button, preferredEdge: NSRectEdge.minY)
}
}
}