简体   繁体   English

在Swift中切换iOS条形按钮标识符(播放/暂停)

[英]Toggling iOS Bar Button identifier (Play/Pause) in Swift

I know similar questions have been asked and answered in the past. 我知道过去也曾问过类似的问题。 However, I seem to have trouble with executing a simple act of toggling the left bar button from Play to Pause. 但是,我似乎无法执行一个简单的动作,即将左栏按钮从“播放”切换为“暂停”。

Here is my code: 这是我的代码:

@IBAction func toggleButton(sender: AnyObject) {
    self.navigationItem.setLeftBarButtonItem(UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Pause, target: self, action: "someFakeAction"), animated: true)
}

func someFakeAction() {
    println("Button pressed")
}

When I tap the Play button, there is a quick fading animation and then the Play button returns. 当我点击“播放”按钮时,会出现快速淡入淡出的动画,然后“播放”按钮返回。 The function someFakeAction is not called. 不调用someFakeAction函数。 What am I doing wrong? 我究竟做错了什么?

Try this: 尝试这个:

  1. Declare UIBarButtonItem globally so that you can access it later. 全局声明UIBarButtonItem,以便以后可以访问它。 lets call it playPauseButton 让我们称之为playPauseButton

  2. Declare a boolean variable globally for keeping track if it is playing or paused, lets call it isPlaying . 全局声明一个布尔变量以跟踪它是在播放还是在暂停,我们称之为isPlaying

  3. From viewDidLoad init isPlaying = true , and playPauseButton with action pauseIt and set it as leftBarButtonItem . 从viewDidLoad初始化isPlaying = true ,并使用具有pauseIt操作的pauseIt并将其设置为leftBarButtonItem

  4. if button is pressed in pauseIt method init isPlaying = false , initialize playPauseButton with a action playIt and set it to leftBarButtonItem . 如果在pauseIt方法init isPlaying = false按下按钮, playPauseButton使用操作playIt初始化playIt并将其设置为leftBarButtonItem

  5. in playIt set isPlaying = true again and init the playPauseButton with action pauseIt . playIt设置isPlaying = true一次初始化的playPauseButton用行动pauseIt

Hope it clear to you. 希望对您清楚。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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