Group Group Group Group Group Group Group Group Group

Your Second Swift 4 & iOS 11 App - Part 34/ Delegate questions


#1

Hello,

I’m making a new topic cause the old one was automatically closed. In the lecture described in the title the tutor is doing something i don’t understand.

He has one view controller CheckListViewController (the list view with the items).
He has a second view controller AddItemViewController. This one has two nav bar buttons that have two IBAction(s).

@IBAction func cancel() {

    navigationController?.popViewController(animated: true)
    delegate?.addItemViewControllerDidCancel(self)

}

@IBAction func done() {
    let item = CheckListItem()
    item.text = texfield.text!
    item.checked = false
    delegate?.additemItemViewController(self, didFinishAdding: item)
}

This view controller file also has a protocol, that’s a delegate that’s implemented by the CheckListViewController:

protocol AddItemViewControllerDelegate: class {
func addItemViewControllerDidCancel(_ controller: AddItemViewController)
func additemItemViewController(_ controller: AddItemViewController, didFinishAdding item: CheckListItem)
}

This is the implementation:

func addItemViewControllerDidCancel(_ controller: AddItemViewController) {
navigationController?.popViewController(animated: true)
}

func additemItemViewController(_ controller: AddItemViewController, didFinishAdding item: CheckListItem) {
    let newRowIndex = items.count
    items.append(item)
    
    let indexPath = IndexPath(row: newRowIndex, section: 0)
    let indexPaths = [indexPath]
    
    tableView.insertRows(at: indexPaths, with: .automatic)
    navigationController?.popViewController(animated: true)
}

Now what i don’t get, is why is he calling in this methods: navigationController?.popViewController(animated: true)

Because he already is calling does methods in the IBAction func from the controller that delegates to this one.

I tried to comment out the code in either one of them, and of course it works fine. But my question is, is this duplication needed? If not where should the pop call be made ?

Thanks, and sorry for the long post.


#3

#4

Hi @swiftwitcher,
The code navigationController?.popViewController(animated: true)
basically is used to pop the current viewController from the top of the Navigation stack.

cheers,