Swift - 如何使用UIBarButtonItem在播放和暂停之间切换



我正在尝试在我的计时器应用程序中使用以下 Swift 代码使用与我相同的按钮启动和暂停。但它不会切换。该按钮在 IDE 中将标识符设置为"播放"。当我运行应用程序时,计时器会正确启动和暂停。但它没有切换按钮。它始终保持为"播放"

@IBAction func pressPausePlay(sender: AnyObject) {
    if playPause == false
    {
            timer.invalidate()
            self.playPauseButtonVar = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Play, target: self, action: "pressPausePlay")
            playPause = true
    }
    else
    {
           timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: Selector("updateTime"), userInfo: nil, repeats: true)
           self.playPauseButtonVar = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Pause, target: self, action: "pressPausePlay")
           playPause = false
    }
}

可以使用此示例方案在"播放"和"暂停"之间切换,用于按钮标题、图像、导航栏、工具栏

import UIKit
import AVFoundation

class ViewController: UIViewController {
      var myPlayer = AVAudioPlayer()

    @IBOutlet var myNaviBar: UINavigationBar! //OUTLET TO NAVIGATION BAR IMPORTANT TO WORK WITH ITS BARBUTTON ITEMS
    @IBOutlet var myToolBar: UIToolbar!

//**************START :Bottom LEFT TOOLBAR Bar Button Item***********/
    @IBAction func toolBarItemPlay(sender: AnyObject) {
        myToolBar.setItems([UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Pause, target: self, action: "toolBarItemPause:")], animated: true)
        myPlayer.play()
    }

    @IBAction func toolBarItemPause(sender: AnyObject) {
        myToolBar.setItems([UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Play, target: self, action: "toolBarItemPlay:")], animated: true)
        myPlayer.pause()
    }
//**************END :Bottom LEFT TOOLBAR Bar Button Item***********/


//**************START :Top LEFT Naivation Bar Button Item***********/
    @IBAction func leftNavgationbarPlay(sender: UIBarButtonItem) {
        myNaviBar.topItem?.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .Pause, target: self, action: "leftNavigationbarPause:")
        myPlayer.play()
    }
    //no need of control drag to this one below because we are calling from the above leftNavgationbarPlay's Selector/action
    @IBAction func leftNavigationbarPause(sender : UIBarButtonItem) {
        myNaviBar.topItem?.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .Play, target: self, action: "leftNavgationbarPlay:")
        myPlayer.pause()
    }
//**************END :Top LEFT Naivation Bar Button Item***********/


//**************START :Top Right Naivation Bar Button Item***********/
    @IBAction func naviPlay(sender: UIBarButtonItem) {
        //change the topright navigation bar item from SystemItem Play '>' to systemitem pause '||'
        //  here I am assigning the top left item Play to Bar button item Pause
        /* ACTION SELECTOR IMPORTANT. IT MUST CALL THE IB ACTION FUNCTION OF PAUSE AND VICEVERSA, WITH ":" */
        myNaviBar.topItem?.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Pause, target: self, action: "naviPause:")
        myPlayer.play()
    }
    @IBAction func naviPause(sender: UIBarButtonItem) {
    myNaviBar.topItem?.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Play, target: self, action: "naviPlay:")
      myPlayer.pause()
    }
//**************END : Top Right Naivation Bar Button Item***********/


//************START :BUTTON IMAGE CHANGE - ">"to "||"************//
    @IBAction func imagePlayButton(sender: UIButton) {
        let chkImage = sender.currentImage!
        if chkImage == UIImage(named: "play.png"){

            sender.setImage(UIImage(named: "pause.png"), forState: .Normal)
            myPlayer.play()
        } else {
            sender.setImage(UIImage(named: "play.png"), forState: .Normal)
            myPlayer.pause()
        }
    }
//************END :BUTTON IMAGE CHANGE - ">"to "||"************//



//************START BUTTON TITLE CHANGE - PLAY to PAUSE************//
    @IBAction func playButton(sender: UIButton) {
        let chkTitle = sender.currentTitle
        if chkTitle == "Play" {
            sender.setTitle("Pause", forState: .Normal)
            myPlayer.play()
        } else {
            sender.setTitle("Play", forState: .Normal)
            myPlayer.pause()
        }
    }
//************END BUTTON TITLE CHANGE - PLAY to PAUSE************//


    @IBAction func naviStop(sender: UIBarButtonItem) {
        myPlayer.stop()
        myPlayer.currentTime = 0
    }
    @IBOutlet var sliderUI: UISlider!

    @IBAction func mySlider(sender: UISlider) {

        myPlayer.volume = sliderUI.value
    }


    override func viewDidLoad() {
        super.viewDidLoad()

        let audioFilePath = NSBundle.mainBundle().pathForResource("ARRehman", ofType: "mp3")
        //need NSURL from string
        do {
            myPlayer = try AVAudioPlayer(contentsOfURL: NSURL(fileURLWithPath: audioFilePath!))
        }
        catch {
            print("Some error")
        }
    }
}

将新实例分配给 self.playPauseButtonVar 后,您需要替换 UIToolbar 中的栏按钮项。

如果您有toolBarnavigationBar网点:

self.toolBar.setItems([self.playPauseButtonVar], animated: true)
// Or
self.navigationBar.setItems([self.playPauseButtonVar], animated: true)

如果您的类继承了 UIViewController:

self.setToolbarItems([self.playPauseButtonVar], animated: true)
// Or
self.navigationItem.setRightBarButtonItem(self.playPauseButtonVar, animated: true)

Yoichi,谢谢你给我指出正确的地方。我删除了"引用出口"下工具栏出口变量(底部工具栏)上的引用。这解决了错误。但是我无法再次添加工具栏出口,如果我添加,错误又回来了!

它通过代码创建栏按钮与我一起工作,这是我的代码

 import UIKit
class ViewController: UIViewController {
@IBOutlet weak var navigationBar: UINavigationBar!
@IBOutlet weak var displayCountLabel: UILabel!
var buttonPause = UIBarButtonItem()
var buttonPlay = UIBarButtonItem()
var count=0
var timer=NSTimer()
override func viewDidLoad() {
    super.viewDidLoad()
    buttonPause = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Pause, target: self, action: "pauseAction")
    buttonPlay = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Play, target: self, action: "playAction")
    self.navigationBar?.topItem?.leftBarButtonItem = buttonPlay
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}
@IBAction func stopTimer(sender: AnyObject) {
    timer.invalidate()
    count = 0
    displayCountLabel.text = "(count)"
    self.navigationBar?.topItem?.leftBarButtonItem = buttonPlay
}
func pauseAction() {
    self.navigationBar?.topItem?.leftBarButtonItem = buttonPlay
    timer.invalidate()
}
func playAction() {
    self.navigationBar?.topItem?.leftBarButtonItem = buttonPause
    timer=NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: Selector("displayCount"), userInfo: nil, repeats: true)
}
func displayCount()
{
    count++
    displayCountLabel.text = "(count)"
}

}

最新更新