Swift - 如何使用UIBarButtonItem在Play和Pause之间切换

时间:2015-03-09 13:11:11

标签: swift toggle 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
    }

}

4 个答案:

答案 0 :(得分:2)

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

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")

        }

    }

}

答案 1 :(得分:1)

在将新实例分配给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)

答案 2 :(得分:0)

Yoichi,谢谢你把我指向了正确的地方。我删除了“引用插座”下的工具栏插座变量(bottomToolBar)上的参考。这解决了错误。但是我无法再次添加工具栏插座,如果我添加,则会出现错误!

答案 3 :(得分:0)

通过代码创建条形按钮,这是我的代码

 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)"
}

}