[英]Swift delegation without storyboard
你好,我有 2 個班級:
第一類是從 UIViewController 繼承的發送者:
class Sender: UIViewController {
// ReceiverDelegate property for communicating with viewmodel //
var delegate: ReceiverDelegate?
// loginButtonClicked - IBAction called after login button clicked //
@IBAction func loginButtonClicked(sender: AnyObject) {
delegate?.didPressLoginWithCredentials("xx", password: "ss")
}
override func viewDidLoad() {
super.viewDidLoad()
Receiver(vc: self)
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
第二類只是像模型這樣的接收器類,而不是 UIViewController:
protocol ReceiverDelegate {
func didPressLoginWithCredentials(username: String, password: String)
}
class Receiver: ReceiverDelegate {
init(vc: Sender) {
vc.delegate = self
}
func didPressLoginWithCredentials(username: String, password: String) {
println("THE MESSAGE")
}
}
我想問一下,這是否是分配代表的好方法。 我需要以某種方式在我的 Sender 內部進行,因為 Receiver 永遠不會被初始化?
我在 Sender 的 viewDidLoad 中分配了我的委托。
如果有更好的方法請幫忙! (也許我應該做類似 var receiver = Receiver() 之類的事情?然后在沒有委托的情況下調用接收器方法?)
它應該更像這樣:
class Sender: UIViewController, ReceiverDelegate {
var receiver: Receiver()
override func viewDidLoad() {
super.viewDidLoad()
receiver.delegate = self
}
func didPressLoginWithCredentials(username: String, password: String) {
println("THE MESSAGE")
}
然后在您的接收器中:
protocol ReceiverDelegate {
func didPressLoginWithCredentials(username: String, password: String)
}
class Receiver: NSObject { //or whatever you're subclassing
weak var delegate: ReceiverDelegate?
init(vc: Sender) {
// your initialization code
}
// loginButtonClicked - IBAction called after login button clicked
@IBAction func loginButtonClicked(sender: AnyObject) {
delegate?.didPressLoginWithCredentials("xx", password: "ss")
}
}
值得注意的是,您的代碼有點令人困惑——我不確定您的接收器應該是什么,但我已經重新安排了您的代碼以正確使用協議/委托。 Receiver 將需要其中的登錄按鈕按鈕,因此它可能是 UIView 的子類。 很難說沒有看到更多。
如果您有一個帶有按鈕的子視圖,並且您希望視圖控制器處理操作,那么上面的代碼就是您要做的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.