2017-03-26 58 views
0

我有一個待辦事項列表應用程序,並且當用戶點擊該任務時,我想要一個複選標記出現在右側(表示任務已完成)。這是TableViewController的代碼:點擊時沒有出現複選標記

import UIKit 

class LoLFirstTableViewController: UITableViewController { 

    var tasks:[Task] = taskData 

    override func viewDidLoad() { 
     super.viewDidLoad() 
     tableView.rowHeight = UITableViewAutomaticDimension 
     tableView.estimatedRowHeight = 60.0 
    } 

    override func didReceiveMemoryWarning() { 
     super.didReceiveMemoryWarning() 
    } 

    override func numberOfSections(in tableView: UITableView) -> Int { 
     return 1 
    } 

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

    @IBAction func cancelToLoLFirstTableViewController(_ segue:UIStoryboardSegue) { 
    } 

    @IBAction func saveAddTask(_ segue:UIStoryboardSegue) { 
     if let AddTaskTableViewController = segue.source as? AddTaskTableViewController { 

      if let task = AddTaskTableViewController.task { 
       tasks.append(task) 

       let indexPath = IndexPath(row: tasks.count-1, section: 0) 
       tableView.insertRows(at: [indexPath], with: .automatic) 
      } 
     } 
    } 

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 
     let cell = tableView.dequeueReusableCell(withIdentifier: "TaskCell", for: indexPath) as! TaskCell 

     let task = tasks[indexPath.row] 
      cell.task = task 


     if task.completed { 
      cell.accessoryType = UITableViewCellAccessoryType.checkmark; 
     } else { 
      cell.accessoryType = UITableViewCellAccessoryType.none; 
     } 

     return cell 
    } 

    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { 
     tableView.deselectRow(at: indexPath, animated: false) 

     var tappedItem = tasks[indexPath.row] as Task 
     tappedItem.completed = !tappedItem.completed 

     tableView.reloadRows(at: [indexPath], with: UITableViewRowAnimation.none) 
    } 

} 

當我運行它時,沒有任何反應,當我點擊任務。我在這裏錯過了什麼?不幸的是,我的Swift能力有很多不足之處。任何幫助將不勝感激,謝謝!

僅供參考,這裏是任務類的代碼:

import UIKit 

struct Task { 
    var name: String? 
    var points: Int 
    var completed: Bool 

    init(name: String?, points: Int, completed: Bool = false) { 
     self.name = name 
     self.points = points 
     self.completed = completed 
    } 
} 

回答

1

的問題是,你更新你的工作方法didSelectRowAt。 A struct是一個值類型。任何更改通常會生成新副本。數組也是一個值類型。因此,當您更新tappedItem變量時,最終會得到新任務的副本,但陣列中的實際並未實際更新。因此,當單元格重新加載時,未修改的任務用於設置單元格。

更新您的代碼如下:

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { 
    tableView.deselectRow(at: indexPath, animated: false) 

    var tappedItem = tasks[indexPath.row] as Task 
    tappedItem.completed = !tappedItem.completed 
    tasks[indexPath.row] = tappedItem // add this line 

    tableView.reloadRows(at: [indexPath], with: UITableViewRowAnimation.none) 
} 
+0

完美!謝謝你rmaddy! –

相關問題