Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
911 views
in Technique[技术] by (71.8m points)

ios - Protocol Delegate Method is not called in Swift

Protocol delegate method is not called..

First View controller code

class ViewController: UIViewController,customDelegate {

  var seconviewcontroller : SecondViewController = SecondViewController()
  @IBOutlet weak var Label: UILabel!
    override func viewDidLoad() {
        super.viewDidLoad()

    seconviewcontroller.delegate = self
}
func didSelectData(_ result: String) {

    Label.text = result
  print("Didselect Data Call")

}

Second view controller code

import UIKit
protocol customDelegate: class {
    func didSelectData(_ result: String)
}

class SecondViewController: UIViewController {
     var delegate: customDelegate?

@IBOutlet weak var secondbutton: UIButton!

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

@IBAction func secondbuttonclick(_ sender: Any) {
     let selectedItem = "naga"

     delegate?.didSelectData(selectedItem)
}

how to call the func didSelectData pls help me

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

As you've already used segue for navigating between views. You can also use that for this example. I give the following as a code sample so that you can track back yourself to detect issue in your code.

enter image description here

First View Controller

import UIKit

class ViewController: UIViewController, SecondVCDelegate {
    @IBOutlet weak var label: UILabel!

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

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if let secondVC = segue.destination as? SecondViewController {
            secondVC.delegate = self
        }
    }        

    func didSelectData(_ result: String) {
        label.text = result
        print(result)
    }
}

Second View Controller

import UIKit

protocol SecondVCDelegate: class {
    func didSelectData(_ result: String)
}

class SecondViewController: UIViewController {
    @IBOutlet weak var button: UIButton!

    weak var delegate: SecondVCDelegate?

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

    @IBAction func buttonTapped(_ sender: UIButton) {
        delegate?.didSelectData("My result")
        dismiss(animated: true, completion: nil)
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...