0

I am new to iOS development and I am working with this tutorial , to create a simple TO-DO list app

I have a view controller to which I have added a UITableView & a UIBarButtonItem. I want to add an item (a title) to the UITableView on the UIBarButtonItem click. I had written the code but I am not sure whats wrong

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
    }
}

and my todoItem.swift file :

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
    }
}

1 Answer 1

1

Assuming addAGroupBtnclicked() is the click handler for your button to add a new task.

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

After changing the data source you need to reload data in order to reflect changes on to UI. For more efficient reloading and reloading part of UITableView check other 'reload' methods of UITableView.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.