控制器之间的委托不起作用。为什么?

Delegate between controllers doesn't work. Why?

我尝试使用委托将数据从 Detail2(ViewController) 中的 textField 发送到 ViewController 中的数组。 我在这里使用打印方法,第一次打印显示一个元素已添加到数组中,但 ViewVillAppear() 下方的第二种打印方法显示数组为空。如何?我希望能够使用委托将数据添加到我的 table。

["sdsd"]首先从控制台打印 []从控制台第二次打印

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {

@IBOutlet var add: UIBarButtonItem!
@IBOutlet var tv: UITableView!
var array :[String] = []

override func viewDidLoad() {
    super.viewDidLoad()

    tv.register(UITableViewCell.self, forCellReuseIdentifier: "cell") 
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "segue" {
        let vc: Detail2 = segue.destination as! Detail2
        vc.delegate = self
    }
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

    return array.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
    cell.textLabel?.text = array[indexPath.row]
    return cell
}
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
    if editingStyle == .delete {
        array.remove(at: indexPath.row )
        tv.reloadData()
    }
}

func alert () {
}



 override func viewWillAppear(_ animated: Bool) {
        tv.reloadData()
        print(array)

    }

}

extension ViewController: Data {

    func tekst(data: String) {
        array.append(data)
        print(array)

    }   
}

细节2

    protocol Data {
    func tekst (data: String)
}

class Detail2: UIViewController {

    var delegate: Data? = nil
    @IBAction func btn(_ sender: Any) {

        let sb  = storyboard?.instantiateViewController(withIdentifier: "Main" ) as! ViewController
        navigationController?.pushViewController(sb, animated: true)

        if delegate != nil {
            if txtfield.text != nil {

                let napis = txtfield.text
                delegate?.tekst(data: napis!)   
            }   
        }   
    }
    @IBOutlet var btn: UIButton!
    @IBOutlet var txtfield: UITextField!

    override func viewDidLoad() {
        super.viewDidLoad()

        btn.backgroundColor = UIColor.blue
        btn.tintColor = UIColor.white
        btn.layer.cornerRadius = 25
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}

只需更新您的函数:

@IBAction func btn(_ sender: Any) {
        if delegate != nil {
        if txtfield.text != nil {
            let napis = txtfield.text
            delegate?.tekst(data: napis!)
        }

    navigationController?.popViewController(animated: true)

    }
}

更新:

extension ViewController: Data {

    func tekst(data: String) {
        array.append(data)
        print(array)
        self.tv.reloadData()

    }   
}

您需要在完成处理程序中添加此 delegate?.tekst(data: napis!),因为您使用的是 navigationController,没有完成处理程序的选项,因此必须添加 UINavigationController 扩展名:

extension UINavigationController {

    public func pushViewController(viewController: UIViewController,
                                   animated: Bool,
                                   completion:  (() -> Void)?) {
        CATransaction.begin()
        CATransaction.setCompletionBlock(completion)
        pushViewController(viewController, animated: animated)
        CATransaction.commit()
    }

}

改变这个

navigationController?.pushViewController(sb, animated: true){

    if delegate != nil {
        if txtfield.text != nil {

            let napis = txtfield.text
            delegate?.tekst(data: napis!)

        }

更新 Detail2 中的代码 viewcontroller

@IBAction func btn(_ sender: Any) {

       if delegate != nil {
           if txtfield.text != nil {
             let napis = txtfield.text
             delegate?.tekst(data: napis!)
            }
        }
        navigationController?.popViewController(animated: true)
}

ViewController中实现委托方法

 func tekst (data: String) { 
    array.append(data)
 }

// 详细

@IBAction func btn(_ sender: Any) {

    if txtfield.text != nil {

        let napis = txtfield.text
        delegate?.tekst(data: napis!)

    }

     /// dismiss detail here  don't push main again

     self.navigationController?.popViewController(animated: true)

}