简体   繁体   中英

How to change the bar button icon in toolbar in swift?

I am trying to toggle between the play button and pause button in swift. I have a bar button item in the toolbar whose identifier is initially set to the play . I tried to search and found out the following piece of code but it does not work, looks like it works when the bar button is in the navigation bar

self.navigationItem.setLeftBarButtonItem(UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Play, target: self, action: "TheMethodThatTheButtonShouldCall"), animated: true)

You need to set items on UIToolbar to update toolbar items: call func setItems(_items: [AnyObject]?,animated animated: Bool) with your new items to update the toolbar's items

Source: https://developer.apple.com/library/prerelease/ios/documentation/UIKit/Reference/UIToolbar_Class/index.html#//apple_ref/occ/instm/UIToolbar/setItems:animated :

Implemented your question with the code as below. works in Swift 2. Please note I connected the IBAction outlet to playBtn

import UIKit
import AVFoundation

class ViewController: UIViewController {

    @IBOutlet var sliderVal: UISlider!
    @IBOutlet var theToolbar: UIToolbar!

    var mySound = AVAudioPlayer()

    override func viewDidLoad() {
        super.viewDidLoad()

        let path = NSBundle.mainBundle().pathForResource("ColdPlay", ofType: "mp3")

        do {
        mySound = try AVAudioPlayer(contentsOfURL: NSURL(fileURLWithPath: path!))
        }
        catch{
            print("error caught")
        }
    }

   @IBAction func playBtn(sender: UIBarButtonItem) {

    let theBarbuttonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Pause, target: self, action: "pauseBtn:")
    let arrayBarButtonItem = [theBarbuttonItem]
    theToolbar.setItems(arrayBarButtonItem, animated: true)


        mySound.play()
    }

    @IBAction func pauseBtn(sender: UIBarButtonItem) {
        let theBarbuttonItemB = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Play, target: self, action: "playBtn:")
        let arrayBarButtonItemB = [theBarbuttonItemB]
        theToolbar.setItems(arrayBarButtonItemB, animated: true)

        mySound.pause()
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM