简体   繁体   中英

Cannot assign value of type NSMutableArray to type UIBarButtonItem

I am developing an iOS audio app as a learning project. I'm having a problem in one of the functions, which checks if the player is playing or paused/stopped. If it's playing it should change the button in the button bar to a "pause" button, or if it's paused or stopped, change the button to a "play" button. I am assigning the button bar items to a variable "items" as a NSMutableArray, then make the necessary change to the button, then assign "items" back to the button bar items to update the display.

In my code I am getting an error on the line:

self.toolbar.items = items

The error message is

Cannot assign value of type NSMutableArray to Type UIBarButtonItem

I assume that I need to cast the NSMutableArray, I've tried using Array, and when I do the error goes away but the buttons break.

The related parts of my code are:

@IBOutlet weak var toolbar: UIToolbar!

@IBOutlet var playButton: UIBarButtonItem!


@IBAction func playPausePressed(sender: AnyObject) {
    let playbackState = self.player.playbackState as MPMusicPlaybackState
    let items = NSMutableArray(array: self.toolbar.items!)
    if playbackState == .Stopped || playbackState == .Paused{
        self.player.play()
        items[2] = self.pauseButton
    } else if playbackState == .Playing{
        self.player.pause()
        items[2] = self.playButton
    }
    self.toolbar.items = items
}

Any help or direction would be much appreciated. Thanks!

The error occurs because NSMutableArray is not related to Swift Array

Why not using the native property directly? Due to reference semantics it's not necessary to create a temporary array.

@IBAction func playPausePressed(sender: AnyObject) {
    let playbackState = self.player.playbackState as MPMusicPlaybackState
    var items = self.toolbar.items!
    if playbackState == .Stopped || playbackState == .Paused{
        self.player.play()
        items[2] = self.pauseButton
    } else if playbackState == .Playing{
        self.player.pause()
        items[2] = self.playButton
    }
}

I have a feeling that you could do better. Do you really need to switch between two different buttons for your items[2] ?

UIBarButtonItem can be used pretty much like a regular UIButton with different states. I'm assuming you'd want to switch between a play and pause image whenever your player is paused/playing. You could do this by setting two different images to your UIBarButtonItem ( setBackgroundImage(_:forState:barMetrics:) ) then by setting the appropriate state when your playbackState changes.

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