Make a UIBarButtonItem disappear using swift IOS

前端 未结 15 2159
慢半拍i
慢半拍i 2020-12-10 23:31

I have an IBOutlet that I have linked to from the storyboard

@IBOutlet var creeLigueBouton: UIBarButtonItem!

and I want to make it disappea

15条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-11 00:19

    If you have set of UIBarButtonItems to hide, e.g. only show them on Landscape orientation, and hide or Portrait, you can use tag and Swift Array's filter. Let's assume we made @IBOutlet link to UIToolBar:

    @IBOutlet weak var toolbar: UIToolbar!
    

    First, we save toolbar's items in viewDidLoad:

    override func viewDidLoad() {
      super.viewDidLoad()
      // Do any additional setup after loading the view, typically from a nib.
      toolbarItems = toolbar.items
    }
    

    Set the tag property of UIBarButtonItem you want to show on Landscape orientation to 1 or whatever you like. Then, override func traitCollectionDidChange

    override func traitCollectionDidChange(previousTraitCollection: UITraitCollection?) {
        super.traitCollectionDidChange(previousTraitCollection)
    
        switch (traitCollection.horizontalSizeClass, traitCollection.verticalSizeClass) {
        case (.Compact, .Regular): // iPhone Portrait
          let items: [UIBarButtonItem]?
          if view.frame.width > 320 { // iPhone 6 & 6S
            items = toolbarItems?.filter({ $0.tag < 5 })
          } else { 
            items = toolbarItems?.filter({ $0.tag < 4 })
          }
          bottomToolbar.setItems(items, animated: true)
        case (_, .Compact): // iPhone Landscape
          let items = toolbarItems?.filter({ $0.tag < 6 })
          bottomToolbar.setItems(items, animated: true)
        default: // iPad
          break
        }
      }
    

    In this example, I set all UIBarButtonItem's tag for iPad only to 6, iPhone Landscape to 5, and for iPhone 6 & 6+ to 4.

提交回复
热议问题