Swift 没有故事板的代表团

Swift delegation without storyboard

你好,我有 2 个 classes :

1st class是一个继承自UIViewController的sender:

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.
}

}

2nd Class 只是 Receiver class 就像一个模型而不是 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 应该是什么,但我已经重新安排了您的代码以正确使用 protocols/delegation。 Receiver 将需要其中的登录按钮按钮,因此它可能是 UIView 的子类。很难说没有看到更多。

如果您有一个带有按钮的子视图,并且您希望视图控制器处理该操作,上面的代码就是您要做的。