简体   繁体   中英

Swift delegation without storyboard

Hello I have 2 classes :

1st class is a sender that inherits from 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 is just Receiver class like a Model and its not a 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")
}

}

I wanted to ask if thats a good approach of assigning a delegate. I need to do it inside my Sender somehow, cause Receiver would never get initialised ?

I assigned my delegate in viewDidLoad of Sender.

If there is any better approach please help ! (perhaps i should just do something like var receiver = Receiver() ? and then just call receiver methods without the delegation ?)

It should be more like this:

class Sender: UIViewController, ReceiverDelegate {

var receiver: Receiver()

override func viewDidLoad() {
    super.viewDidLoad()
    receiver.delegate = self
}

func didPressLoginWithCredentials(username: String, password: String) {
    println("THE MESSAGE")
}

Then in your receiver:

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")
    }
}

Its worth noting your code is a little confusing - i'm not sure what your Receiver is supposed to be, but i've rearranged your code to correctly use protocols/delegation. The Receiver will need that login button button in it, so its probably a subclass of UIView. Hard to say without seeing more.

The code above is what you would do if you have a child view with a button in it, and you want the view controller to handle the action.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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