4

I am implementing accessibility into our current project and have some issues on setting focus on an element in a previous viewcontroller.

An example would be:

A user selects on a tableview cell at index 3. In didSelectRowAt, we present to the user a UIActionSheet where the user makes a selection. Once the user makes a selection and the presented UIActionSheet is dismissed, the accessibility focus SHOULD be selected at tableview cell index 3, but instead the focus is set back to the initial element in the view, in my case most top-left element.

I have used UIAccessibility.Notification .screenChanged and UIView.accessibilityViewIsModalto set a new focus when presenting a modal view, but this doesn't seem to have a good solution to point back to a previous element when dismissing a view.

Any insight on how to track the previous accessibility element focus would be greatly appreciated.

BearBearBear
  • 109
  • 3
  • 9

1 Answers1

3

First, create a variable that will store the previous position in the TableViewController:

var previousPosition: IndexPath?

Then, store this position once you tap on a cell:

override func tableView(_ tableView: UITableView,
                        didSelectRowAt indexPath: IndexPath) {

    previousPosition = indexPath
}

Finally, when the presented UIActionSheet is dismissed (example of a back button hereafter), the following code snippet selects and focuses the table view cell from which the latest tap has been triggered:

var actionSheet: UIAlertController?

actionSheet = UIAlertController(title: "Action Sheet",
                                message: "Ready to go back?",
                                preferredStyle: .actionSheet)

let backButton = UIAlertAction(title: "B.A.C.K.",
                               style: .cancel,
                               handler: { (action) -> Void in

        print("Back button tapped")

        self.tableView.selectRow(at: self.previousPosition,
                                 animated: true,
                                 scrollPosition: .none)

       let currentCell = self.tableView.cellForRow(at: self.previousPosition!)

       UIAccessibility.post(notification:.layoutChanged,
                            argument: currentCell)
})

actionSheet!.addAction(backButton)

Check out the result of this code snippet in a blank project and adapt it in your app to make it work as desired.

EDIT: besides my code snippet, take a look at the remembersLastFocusedIndexPath instance property of the table view that may provide the direct result in conjunction with the restoresFocusAfterTransition instance property of the view controller.

XLE_22
  • 5,124
  • 3
  • 21
  • 72