How to programmatically replace UIToolBar items built in IB

后端 未结 8 880
我在风中等你
我在风中等你 2020-12-13 21:35

I have a toolbar with various image buttons, created in Interface Builder.

I\'d like to be able to programmatically replace one of the buttons with an activity indic

相关标签:
8条回答
  • 2020-12-13 22:36

    Swift has a much easier way. In my case, I am switching the play button with the pause button every touch.

    @IBAction func playandPause(sender: UIBarButtonItem) { // Here we are creating an outlet. Hook this up to the bar button item.
        for (index, button) in toolbarItems!.enumerate() { // Enumerating through all the buttons
            if button === sender { // === operator is used to check if the two objects are the exact same instance in memory.
                var barButtonItem: UIBarButtonItem!
                if mediaplayer.playing {
                    mediaplayer.pause()
                    barButtonItem = UIBarButtonItem.init(barButtonSystemItem: .Play, target: self, action: #selector(playandPause(_:)))
                }else {
                    mediaplayer.play()
                    barButtonItem = UIBarButtonItem.init(barButtonSystemItem: .Pause, target: self, action: #selector(playandPause(_:)))
                }
                toolbarItems![index] = barButtonItem // Replace the old item with the new item.
                break // Break once we have found the button as it is unnecessary to complete the rest of the loop
            }
        }
    }
    
    0 讨论(0)
  • 2020-12-13 22:37

    A note on this - the toolbar will strip out any color in your icons, so you still won't be able to make it yellow. You'll need to change the image shape to indicate "on" instead.

    Alternatively you'll need to load your BarButtonItems with UIButtons (use the initWithCustomView) and set the image of the button appropriately.

    HTH

    0 讨论(0)
提交回复
热议问题