简体   繁体   English

如何知道是否按下了UIBarButtonItem?

[英]How to know if UIBarButtonItem is pressed?

I have tried numerous options for this code to work but I don't find a proper way. 我已经尝试了许多选项来使此代码正常工作,但找不到合适的方法。 I know that this method works with UIButtons but with UIBarButtonItems it seems is different. 我知道此方法可与UIButtons一起使用,但与UIBarButtonItems似乎不同。

@IBOutlet weak var stopOutlet: UIBarButtonItem!

@IBAction func stop(sender: AnyObject) {

    if stopOutlet.selected {

        player.stop()

    } else {

        player.play()

        do {
            try player = AVAudioPlayer(contentsOfURL: NSURL(fileURLWithPath: audioPath))

        } catch {
            print("Unable to play the file. Please try another song")
        }
    }
}

The line of code that does not work is the following 无效的代码行如下

if stopOutlet.selected

Is there any boolean that works with UIBarButtonItems??? 有没有可以与UIBarButtonItems一起使用的布尔值???

Im just starting to learn swift and Xcode so sorry if the question is lame. 我刚刚开始学习swift和Xcode,所以很抱歉,如果这个问题很la脚。

You need to maintain some external state which tracks what the last button press did, or better infer it from the the state of the audioPlayer. 您需要维护一些外部状态,以跟踪上次按下按钮的行为,或者更好地从audioPlayer的状态推断出来。 This state can also be used to drive the text the button displays (play/pause) 此状态也可用于驱动按钮显示的文本(播放/暂停)

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

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