项目添加到UITableView的按钮点击iOS中斯威夫特

问题描述:

我是新来的iOS开发和我与this教程的学习,创建一个简单的待办事项列表应用项目添加到UITableView的按钮点击iOS中斯威夫特

我有我有一个视图控制器添加了UITableView & UIBarButtonItem。我想添加一个项目(标题)到UIBarButtonItem点击UITableView。我写的代码,但我不知道什么是错

class contactsMenu: UIViewController, UITableViewDataSource , UITableViewDelegate { 

    @IBOutlet weak var tableView: UITableView! 

    var toDoItems = [todoItem]() 
    override func viewDidLoad() { 
     super.viewDidLoad() 
     tableView.dataSource = self 
     tableView.delegate = self 
     tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "cell") 
     if toDoItems.count > 0 { 
      return 
     } 
    } 

    override func viewDidAppear(animated: Bool) { 
     tableView.reloadData() 
    } 



    @IBAction func addAGroupBtnclicked(sender: UIBarButtonItem) { 
     toDoItems.append(todoItem(text: "ok")) 
    } 

    @IBAction func backBtn(sender: UIBarButtonItem) { 
     self.dismissViewControllerAnimated(true, completion: nil) 
    } 

    func numberOfSectionsInTableView(tableView: UITableView) -> Int { 
     return 1 
    } 

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

    func tableView(tableView: UITableView, 
     cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { 
      let cell = tableView.dequeueReusableCellWithIdentifier("cell", 
       forIndexPath: indexPath) as UITableViewCell 
      let item = toDoItems[indexPath.row] 
      cell.textLabel?.text = item.text 
      return cell 
    } 
} 

和我todoItem.swift文件:

class todoItem : NSObject{ 

    var text: String 

    // A Boolean value that determines the completed state of this item. 
    var completed: Bool 

    // Returns a ToDoItem initialized with the given text and default completed value. 
    init(text: String) { 
     self.text = text 
     self.completed = false 
    } 
} 

假设addAGroupBtnclicked()是你的按钮,添加一个新的任务单击处理程序。

@IBAction func addAGroupBtnclicked(sender: UIBarButtonItem) { 
    toDoItems.append(todoItem(text: "ok")) 
    tableView.reloadData() 
} 

更改数据源后,需要重新加载数据以反映UI上的更改。为了更有效地重载和重载UITableView的一部分,请检查UITableView的其他“重载”方法。