简体   繁体   中英

Swift - Delegate method with TabBar

I have a very simple project where one View (Sending view) should change appearance of second View (Receiving view). I am trying to use delegation but I have a problem with assign variable "delegate" in SendingVC. I tried to do it in override func "prepare" in ReceivingVC, but this method is not called.

I think this code could work, but I don't know where I should put it:

let sendVC : SendingVC! = tabBarController?.viewControllers![1] as! SendingVC
sendVC.delegate = self

ReceivingVC:

import UIKit

class ReceivingVC: UIViewController, DataSendDelegate {

@IBOutlet weak var Label: UILabel!

func userDidEnterData(data: String) {
    Label.text = data
}

override func viewDidLoad() {
    super.viewDidLoad()
}

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    let sendVC : SendingVC! = tabBarController?.viewControllers![1] as! SendingVC
    sendVC.delegate = self
}
}

SendingVC:

import UIKit

protocol DataSendDelegate {
func userDidEnterData(data: String)
}

class SendingVC: UIViewController {
var delegate: DataSendDelegate? = nil

override func viewDidLoad() {
    super.viewDidLoad()
}

@IBAction func setTextButton(_ sender: UIButton) {
    if delegate != nil {
        delegate?.userDidEnterData(data: "some text")
    }
}
}

Storyboard img

Thanks bjd23, it works perfectly. So solution is put it to the viewDidLoad method

Edit: If you have this code:

if delegate != nil {
    delegate?.userDidEnterData(data: "some text")
}

in the viewDidLoad instead of button action, I recommend to put it to the viewDidAppear or viewWillAppear, because if your Sending view is loaded first, nothing will happen

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