How to programmatically replace UIToolBar items built in IB

后端 未结 8 881
我在风中等你
我在风中等你 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
            }
        }
    }
    

提交回复
热议问题