How do I show/hide a UIBarButtonItem?

前端 未结 30 2323
执念已碎
执念已碎 2020-11-28 01:18

I created a toolbar in IB with several buttons. I would like to be able to hide/show one of the buttons depending on the state of the data in the main window.

30条回答
  •  盖世英雄少女心
    2020-11-28 02:08

    I discovered another wrinkle in the tintColor and isEnabled approach suggested by Max and others - when VoiceOver is enabled for accessibility and the button is logically hidden, the accessibility cursor will still focus on the bar button, and state that it is "dimmed" (i.e. because isEnabled is set to false). The approach in the accepted answer doesn't suffer from this side-effect, but another work around I found was to set isAccessibilityElement to false when "hiding" the button:

    deleteButton.tintColor = UIColor.clear
    deleteButton.isEnabled = false
    deleteButton.isAccessibilityElement = false
    

    And then setting isAccessibilityElement back to true when "showing" the button:

    deleteButton.tintColor = UIColor.blue
    deleteButton.isEnabled = true
    deleteButton.isAccessibilityElement = true
    

    Having the bar button item still take up space was not an issue in my case, since we were hiding/showing the left-most of right bar button items.

提交回复
热议问题