I have two sets of toolbar items that should be shown, depending on whether editing is enabled. When the edit button is tapped, the toolbar (and navigation bar items as well) should change to the appropriate set of items. I do this by calling this function inside my override of setEditing(_:animted:)
:
func configureToolbarItems(isEditing: Bool, animated: Bool) {
func flexibleSpace() -> UIBarButtonItem {
return UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
}
if isEditing {
navigationController?.toolbar.setItems([deleteSelectedItemsItem,
flexibleSpace(),
addToCollectionButtonItem,
flexibleSpace(),
shareBarItem], animated: animated)
navigationItem.setLeftBarButtonItems([selectAllBarButtonItem], animated: animated)
} else {
navigationController?.toolbar.setItems([organizeButton,
flexibleSpace(),
addButton], animated: animated)
navigationItem.setLeftBarButtonItems([settingsBarButtonItem, layoutButton], animated: animated)
}
}
There were no problems using this... until iOS 13. On iOS 13, when scrolling to the top of the collection view, the toolbar items get reset to the toolbar items that are set in the storyboard, causing the wrong set of items to be displayed.
I tested this by adding a new toolbar item on the storyboard that isn't used for anything. When the code above is called, the toolbar gets set correctly, but scrolling to the top makes the test bar button item appear on the toolbar again. Here's a video (with the item only set from the storyboard being the one just called ("Item"):
The same code works as expected on iOS 12 and below. I've tried overriding scrollViewDidScrollToTop(_ scrollView:)
and scrollViewDidScroll(_:)
and calling my configureToolbarItems
function there, but neither worked.