如何在按钮操作中的TableViewController中重新加载tableview?

时间:2016-07-01 15:10:24

标签: ios swift uitableview

目前我有以下代码保存对象,但我想更新/重新加载tableview。该按钮没有连接到我导航控制器右上角的单元格/行(加上图标)

注意:所有事情都发生在同一场景中,因此任何附加到segue的事件都无法重新加载表格数据。

    @IBAction func addWeek (sender: UIButton){

    let newnumber:Int = routineWeeks.count + 1

    // save data using cor data managed object context
    if let managedObjectContext = (UIApplication.sharedApplication().delegate as? AppDelegate)?.managedObjectContext {
        week = NSEntityDescription.insertNewObjectForEntityForName("Weeks", inManagedObjectContext: managedObjectContext) as! Weeks

        week.weekNumber = newnumber

        do {
            try managedObjectContext.save()
        } catch {
            print(error)
            return
        }
    }

    //currently not reloading table with new data
    tableView.reloadData()

    //print information in console

    print("end of save function, dismiss controller")

}

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

    let cellIdentifier = "Cell"
    let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath)

    // Configure the cell...
    cell.textLabel?.text = "Week \(routineWeeks[indexPath.row].weekNumber)"

    return cell
}

更新 感谢Stackoverflow社区指出我正确的方向。

routineWeeks.append(week)
print("this is a new week:\(week)")
tableView.reloadData()

4 个答案:

答案 0 :(得分:0)

你似乎永远不会在“常规周刊”中添加“周”。

编辑: 您应该在tableView.reloadData之前的routineWeeks(来自CoreData)中重新加载数据。

答案 1 :(得分:0)

我不知道它是否会对您有所帮助,但我遇到了同样的问题,我添加了Refresher(添加“拉动刷新”功能)

在我班上:

override func viewDidLoad() {
        super.viewDidLoad()

        // Pull to refresh - DEBUT
        tableFiches.addPullToRefreshWithAction {
            NSOperationQueue().addOperationWithBlock {
                //sleep(1)
                NSOperationQueue.mainQueue().addOperationWithBlock {
                    self.loadMyData() // My func here to load data
                    self.tableFiches.stopPullToRefresh()
                }
            }
        }
        // Pull to refresh - FIN

    }

func loadMyData(){
   // request here
   let recupJSON = JSON(value) // my data
   if let resData = recupJSON["Data"].arrayObject {
                        //print("OK2")
   self.ArrayFiches = resData as! [[String:AnyObject]] // Attribute  json ==> ArrayFiches
   }
  if self.ArrayFiches.count > 0 {
    self.tableFiches.reloadData()
  }
}

当我想重新加载我的数据时,我使用:

tableFiches.startPullToRefresh()

它有效:)

答案 2 :(得分:0)

您没有更新routineWeeks数组。在重新加载tableView之前用新数据更新它。

答案 3 :(得分:0)

routineWeeks.append(week)
print("this is a new week:\(week)")
tableView.reloadData()