Swift委托没有故事板

时间:2015-09-25 16:32:27

标签: ios swift delegates parameter-passing

您好我有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.
}

}

2nd Class就像Model一样只是Receiver类而不是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")
}

}

我想问一下这是否是分配代表的好方法。我需要以某种方式在发件人内部进行,因为Receiver永远不会被初始化?

我在发信人的viewDidLoad中分配了我的委托。

如果有更好的方法,请帮忙! (也许我应该做一些像var receiver = Receiver()?然后只调用没有委托的接收方法?)

1 个答案:

答案 0 :(得分:2)

应该更像这样:

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的子类。很难说没有看到更多。

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