Swift - 添加到阵列后不能重新加载tableView

问题描述:

我在更新我的UITableView时遇到问题。我有一个应用程序,基本UIViewController与导航项“添加新项目”UITableViewContioller。我可以添加字符串,然后转储数组以查看是否已添加。转储功能显示阵列中添加的项目,但UITableView不会,即使在致电reloadData后。这是我的代码。Swift - 添加到阵列后不能重新加载tableView

enter image description here

这里是打保存后控制台转储。

enter image description here

所以你可以看到的东西是有我保存后,但没有显示出来的UITableview

UIViewController类我有一个UIAlertAction接受文本和保存按钮。

 let table = TableViewController() 


     let saveAction = UIAlertAction(title: "Save", style:UIAlertActionStyle.Default, handler: { 
     alert -> Void in 

     let firstTextField = alertController.textFields![0] as UITextField 
     self.table.cityArry.addObject(firstTextField.text!) 
     self.table.refresh() 
    }) 

而且从UITableViewController

class TableViewController: UITableViewController { 

var cityArry:NSMutableArray = ["Local"] 

override func viewDidLoad() { 
    super.viewDidLoad() 
    tableView.delegate = self 
    tableView.dataSource = self 

} 


func refresh(){ 
    dump(cityArry) 
    tableView.reloadData() 
} 

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

} 

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { 
    let item = cityArry[indexPath.row] 
    let cell = UITableViewCell() 
    let label = UILabel(frame: CGRect(x:20, y:0, width:200, height:50)) 
    label.text = item as? String 
    cell.addSubview(label) 

    return cell 
} 

override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { 


    // Nothing here yet 

} 
} 
+0

你确定屏幕上显示的'table'是你调用'refresh'的那个? –

尝试改变这一点:

func refresh(){ 
    dump(cityArry) 
    tableView.reloadData() 
} 

这样:

func refresh(){ 
    dispatch_async(dispatch_get_main_queue()) {() -> Void in 
     dump(cityArry) 
     self.tableView.reloadData() 
    } 
} 

如果碰巧refresh()获取调用除了主线程以外,表视图可能无法正确更新。可能不是问题,但它是一个好的第一步。

您需要在刷新函数中重新加载主线程中的数据。

dispatch_async(dispatch_get_main_queue(), {() -> Void in 
self.tableView.reloadData() 
}) 

我不认为你应该有你要显示在屏幕两个独立的视图控制器。简化可能最终会像@ J.Wang所说的那样解决你在不同对象上调用方法的问题。您的屏幕应该使用添加了按钮的导航控制器中嵌入的TableViewController进行处理。