1

I'm creating a Master-Detail view app that is managed by a split view controller. I am passing model data from the master view controller through the segue function, and returning it from the detail view controller via a delegate method (which simply gets the data from the text fields and returns the object). This works fine when the view controllers are collapsed, but when they are not I get undesired behaviour because of the way I pass back and save information.

I've tried sending back information on viewWillDisappear, however when both views are showing this does not work as you can click in between the views without the view of the detail controller disappearing. At the moment, I am trying to call the delegate function to save the data when textFieldShouldEndEditing. However, I just found out if I am still editing a text field and click another cell in the table view, then the data gets saved in the clicked cell since the selected index changes and then the delegate function is called.

Save function within Master View Controller:

func saveItem(item: Item) {

        if let selectedIndexPath = tableView.indexPathForSelectedRow {

            // Update existing item and reselect current row
            items[selectedIndexPath.row] = item
            tableView.reloadRows(at: [selectedIndexPath], with: .automatic)
            tableView.selectRow(at: selectedIndexPath, animated: false, scrollPosition: UITableView.ScrollPosition(rawValue: 0)!)
        }
}

textFieldShouldEndEditing within the DetailViewController:

func textFieldShouldEndEditing(_ textField: UITextField) -> Bool {

        let nameFieldString = nameField.text ?? "New Item"

        // Initialize Item object
        let newItem = Item(name: nameFieldString)

        // Call protocol function to pass Item object to delegate
        if delegate != nil {
            delegate?.saveItem(item: newItem)

            // Update the DetailViewController's item variable
            detailItem = newItem
        }

    return true
}

I assume that there must be a standard way, or simple way, to pass information between the two view controllers while implementing a split view controller.

Perhaps there is a better way to go about saving edits to items than using tableView.indexPathForSelectedRow to track the currently selected item. Or better triggers (rather than textFieldShouldEndEditing) to use to determine when to save edits from the detail view back to the master view.

I am wanting to use delegation. Any guidance would be much appreciated.

  • Here is right answer on the top. https://stackoverflow.com/questions/5210535/passing-data-between-view-controllers?rq=1 – Agisight Apr 05 '19 at 15:15
  • Also you can set a new property `Item` to your custom class of UISplitViewController and get it in Detail view controllers from parent controller (as UISplitViewController. – Agisight Apr 05 '19 at 15:19

0 Answers0