Tableview不会reloadData()

时间:2016-06-09 01:04:03

标签: ios swift delegates tableview protocols

Sup人?需要一些帮助。我使用委托协议将一些字符串从“第二个视图控制器”传递回它的前一个字符串。

我的数组附加了我在委托协议上实现的方法中的字符串,但每次按“添加”并返回第一个屏幕时,表视图不会更改。我不确定字符串是否在视图之间传递,或者它是否只是没有重新加载的表视图。

代码非常简单:

import UIKit

class EsseVaiReceber: UIViewController, UITableViewDataSource, UITableViewDelegate, PassInfoDelegate   {

    @IBOutlet var listaDeCoisasAFazer: UITableView!
    var arrayInfo : [String] = []
    var stringReceived: String = ""

    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)
        listaDeCoisasAFazer.reloadData()
        print("SCREEN APPEARED")

    }

    override func viewDidLoad() {
        super.viewDidLoad()
        listaDeCoisasAFazer.reloadData()
        print("LOADED SCREEN")
    }

    func passInfo(infothatwillpass: String) {
        arrayInfo.append(infothatwillpass)
    }


    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return arrayInfo.count
    }

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as UITableViewCell!
        let row = indexPath.row
        let titulo = arrayInfo[row]
        cell.textLabel!.text = titulo

        return cell
    }

    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        if(segue.identifier == "add") {
            let view = segue.destinationViewController as! EsseVaiPassar
                view.delegate = self
        }
    }

}

和:

import Foundation
import UIKit

protocol PassInfoDelegate {
    func passInfo(infothatwillpass: String)

}

class EsseVaiPassar: UIViewController {

    @IBOutlet var campoTitulo: UITextField!
    var delegate: PassInfoDelegate?
    var textinput: String = ""


    @IBAction func botaoAdicionarCoisasAFazer(sender: AnyObject) {

        if campoTitulo == nil { return }
        textinput = campoTitulo!.text!
        print("TEXTO NO CAMPO:\(textinput)")

        if delegate == nil {
            print("DELEGATE IS NILL")
            return
    }

        delegate!.passInfo(textinput)
        print("TEXTO DO DELEGATE: \(textinput)")

        if let navigation = self.navigationController {
            navigation.popViewControllerAnimated(true)
            print("INFO QUE VAI PASSAR: \(textinput)")
        }
    }
}

为什么表格视图不会填充的任何想法?谢谢高级=)

1 个答案:

答案 0 :(得分:1)

tableView使用arrayInfo作为listaDeCoisasAFazer tableView数据的源(间接)。如果您更改arrayInfo,则需要告知listaDeCoisasAFazer reloadData()

func passInfo(infothatwillpass: String) {
    arrayInfo.append(infothatwillpass)
}

您可以/应该从reloadData()viewWillLoad移除viewDidLoad,因为数据源尚未更改,因此无需重新加载数据。

提示

您正在目标viewController中的nil调用之前检查delegate。除非您出于调试目的而这样做,否则只需拨打delegate?.passInfo(textinput)即可。如果委托是nil,它将忽略该调用。