繁体   English   中英

没有故事板的 Swift 委托

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM