Saturday, November 18, 2017

iOS 11 UIBarButtonItem may not work on real device

One iOS project has a view controller containing a table view and a toolbar, the toolbar has a UIBarButtonItem to open another view controller.

After upgrading an old ios project with XCode 9.1 and swift 4, running it on iOS 11 real device shows clicking on the UIBarButtonItem does not work as expected. However when running on iOS 11 simulator, clicking on the button works fine.

Even if after reverting all the change made during the upgrading in the project, the issue still happens, so it indicates the issue is caused by rebuilding the project using the ios 11 SDK and running it on ios 11 device.

The more investigation indicates the issue is caused by a tap gesture recognizer added in the viewcontroller's view object. The tap gesture is used for dismissing the keyboard.

In ios build prior to iOS 11, even if adding a tap gesture recognize on the view controller's view object, the toolbar button's handle will still be called. However, in iOS 11 sdk, when clicking the button, only the tap gesture recognizer's handler will be called, the button item's click handler will not be called.

The fix is quite simple, instead of adding the gesture recognizer to the view controller's view object, just add it to the tableview' view object. So that when clicking on the bar button item, it will not trigger the tap gesture recognizer's event handler

Original code:
let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(TravelDateViewController.handleTap(recognizer:)))

self.view.addGestureRecognizer(tap)

After the fix:
let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(TravelDateViewController.handleTap(recognizer:)))

self.tableView.addGestureRecognizer(tap)

No comments:

Post a Comment