Tableview reloadData()不起作用

时间:2018-01-08 15:30:11

标签: swift uitableview uialertcontroller uialertaction

任何人都可以帮助我吗?我正在使用tableView并尝试使用Bar Button项目输入用户输入的值,但每当我点击save alert action时,self.tableView.reloadData()都不起作用!

代码如下:

import UIKit  
class ViewController: UIViewController {  
var names:[String]=[]  
@IBOutlet weak var tableView: UITableView!  
override func viewDidLoad() {  
    super.viewDidLoad()  
    self.title="The List"  
    tableView.register(UITableViewCell.self, forCellReuseIdentifier: 
"Cell")  
}  

@IBAction func addName(_ sender: UIBarButtonItem) {  
    let alert = UIAlertController(title: "New Name",  
                                  message: "Add a new name",  
                                  preferredStyle: .alert)  

    let saveAction = UIAlertAction(title: "Save",  
                                   style: .default) {  
                                    [unowned self] action in  

                                    guard let textField = 
                                    alert.textFields?.first,  
                                        let nameToSave = textField.text 
                                         else {  
                                            return  
                                    }  

                                    self.names.append(nameToSave)  
                                    self.tableView.reloadData()  
    }  

    let cancelAction = UIAlertAction(title: "Cancel",  
                                     style: .default)  

    alert.addTextField()  

    alert.addAction(saveAction)  
    alert.addAction(cancelAction)  

    present(alert, animated: true)  

}  
}  
extension ViewController:UITableViewDataSource{  
func tableView(_ tableView: UITableView, numberOfRowsInSection section: 
   Int) -> Int {  
    return names.count  
}  
func tableView(_ tableView: UITableView,cellForRowAt indexPath: 
  IndexPath)-> UITableViewCell {  

        let cell = tableView.dequeueReusableCell(withIdentifier: 
  "Cell",for: indexPath)  
        cell.textLabel?.text = names[indexPath.row]  
        return cell  
  }  
}      

任何人都可以找到这个错误吗?

2 个答案:

答案 0 :(得分:0)

您必须设置委托/数据源才能使用UITableViewDataSource和UITableViewDelegate方法。

您可以在Interface Builder中执行此操作,右键单击表视图,并将delegate / datasource链接到ViewController。

或者您可以在viewDidLoad中的代码中执行此操作:

tableView.delegate = self

答案 1 :(得分:0)

我建议首次加载该视图控制器时验证是否正在调用数据源方法(例如,numberOfRowsInSection)。因此,您在确认是否确实调整了reloadData之后,确实确实已经确定了相应的数据源,并且当您点击“保存'警报行动。我用您的代码设置了一个项目,一切正常:在UIAlertController中添加了一个名称,点击了' Save',调用了reloadData,表格显示了新名称。只需将其添加到viewDidLoad:

tableView.dataSource = self

还要确保您的tableview单元格在界面构建器中指定了其重用标识符。选择表格视图单元格,然后在“属性”检查器中确保'标识符'字段使用您在代码中设置的相同名称填充(例如,forCellReuseIdentifier)。

希望这有帮助。

相关问题