Change bar button Item from Play to Pause Swift - ios

I'm creating a Pomodoro Timer. And I want change the Play bar button item to Pause when I press on it. I've already created the IBOutlet for this button and IBAction.
#IBOutlet weak var playButton: UIBarButtonItem!
#IBAction func startTimer(sender: AnyObject) {
self.playButton = UIBarButtonItem(barButtonSystemItem: .Pause, target: self, action: nil)
}
But this doesn't work. Please help.

try this,
func play() {
var pauseButton = UIBarButtonItem(barButtonSystemItem: .Pause, target: self, action: "pause") //Use a selector
navigationItem.rightBarButtonItem = pauseButton
//other stuff
}
func pause() {
var playButton = UIBarButtonItem(barButtonSystemItem: .Play, target: self, action: "play") //Use a selector
navigationItem.rightBarButtonItem = playButton
//other stuff
}

Related

How to toggle Play and Pause with a UIBarbuttonItem

Can anyone help me. I've search for my question and still can't figure out a solution, everything I found was not formatted in swift 3. Im trying to make a toggle Play and Pause out of a UIBarButtonItem. Whenever the play button is click I want it to play the file and at the same time change the UIBarButtonItem to pause and vise versa.
By the way I have embed in a navigation controller into my main view controller from the editor.
Here is my Code Snippet.
import UIKit
import AVFoundation
class ViewController: UIViewController {
#IBOutlet weak var pausePlayBtn: UIBarButtonItem!
var audioPlayer = AVAudioPlayer()
override func viewDidLoad() {
super.viewDidLoad()
prepareMusic()
}
func prepareMusic() {
let path = Bundle.main.path(forResource: "SomeFileName", ofType: "TypeOfFile")!
do {
audioPlayer = try AVAudioPlayer(contentsOf: URL(fileURLWithPath: path))
audioPlayer.prepareToPlay()
} catch let err as NSError {
print(err)
}
}
#IBAction func togglePausePlay(sender: UIBarButtonItem) {
if !audioPlayer.isPlaying {
audioPlayer.play()
} else {
audioPlayer.stop()
}
}
}
I've tried the following.
First I started by creating play button and a pause button and adding them in my togglePausePlay func.
let playBtn = UIBarButtonItem(barButtonSystemItem: .play, target: self, action: nil)
let pauseBtn = UIBarButtonItem(barButtonSystemItem: .pause, target: self, action: nil)
#IBAction func togglePausePlay(sender: UIBarButtonItem) {
if !audioPlayer.isPlaying {
audioPlayer.play()
pausePlayBtn = playBtn
} else {
audioPlayer.stop()
pausePlayBtn = pauseBtn
}
}
The second thing I tried was this.
#IBAction func togglePausePlay(sender: UIBarButtonItem) {
if !audioPlayer.isPlaying {
audioPlayer.play()
self.navigationController?.navigationBar.topItem?.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .play, target: self, action: nil)
} else {
audioPlayer.stop()
self.navigationController?.navigationBar.topItem?.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .pause, target: self, action: nil)
}
}
This work at the start of the app, I would click the button for the first time and everything would work the button would change to pause and file would start. However when I tried to click it again nothing happens, button stays on pause and file still keeps playing until I stop the project.
Any help would be appreciated. :)
i figured out a solution for u and its working for me.
Here's the code i tried and its working. the buttonitem is changing on its click.
import UIKit
class ViewController: UIViewController {
var playBtn = UIBarButtonItem()
var pauseBtn = UIBarButtonItem()
#IBOutlet var labelMusicState: UILabel!
override func viewDidLoad()
{
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.playBtn = UIBarButtonItem(barButtonSystemItem: .play , target: self, action: #selector(playBtnAction(sender:)))
self.pauseBtn = UIBarButtonItem(barButtonSystemItem: .pause , target: self, action: #selector(pauseBtnAction(sender:)))
self.navigationItem.rightBarButtonItem = playBtn
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func playBtnAction(sender: UIBarButtonItem)
{
self.navigationItem.rightBarButtonItem = pauseBtn
self.labelMusicState.text = "Music is Playing"
}
func pauseBtnAction(sender: UIBarButtonItem)
{
self.navigationItem.rightBarButtonItem = playBtn
self.labelMusicState.text = "Music Not Playing"
}
}
In both the scenarios, you are trying to assign .play button to your existing button whenever the player starts playing music. It should be opposite. whenever the player starts playing music, your button should change to .pause mode and when the player stops playing music, the button should go to .play mode.
do the following modification:
let playBtn = UIBarButtonItem(barButtonSystemItem: .play, target: self, action: nil)
let pauseBtn = UIBarButtonItem(barButtonSystemItem: .pause, target: self, action: nil)
#IBAction func togglePausePlay(sender: UIBarButtonItem) {
if !audioPlayer.isPlaying {
audioPlayer.play()
pausePlayBtn = pauseBtn
} else {
audioPlayer.stop()
pausePlayBtn = playBtn
}
}
You were doing the opposite due to which once the music starts playing, the button does not change its state from play to pause but remains in play state due to which the next time user presses the button, it plays the music and doesnt stop it.

Change BarButtonItem icon on click

I'm trying to create a counter. The idea is quite simple, you click on "play" button and once you click it should disappear and become a "pause" icon, which would trigger a different action.
I thought setting a var for counter status and changing the icon (with only one button) would do the trick but I don't have a clue how can I set the button image for "pause" or any other that appears in the drop down menu when you are creating it from the storyboard panel.
Here the code:
#IBOutlet weak var playButton: UIBarButtonItem!
var timer = NSTimer()
var currentStatus = "stopped"
#IBAction func playAction(sender: AnyObject) {
if (currentStatus == "stopped"){
timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: Selector("increaseTimer"), userInfo: nil, repeats: true)
currentStatus = "running"
// change button icon (playButton) to Stop
}
else {
currentStatus = "stopped"
timer.invalidate()
// change button icon (playButton) to Play
}
}
You can set the button style like this:
//setButton to play
yourBarButtonItem = UIBarButtonItem(UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Play, target: self, action: "TheMethodThatTheButtonShouldCall"), animated: true)
//setButton to stop
yourBarButtonItem = UIBarButtonItem(UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Stop, target: self, action: "TheMethodThatTheButtonShouldCall"), animated: true)
You can set the button style with array like this:
func addCustomNavigationItemAtLeftAndRightSide(leftButtonItems:[UIBarButtonItem], rightButtonItems:[UIBarButtonItem]) {
self.navigationItem.leftBarButtonItems = leftButtonItems
self.navigationItem.rightBarButtonItems = rightButtonItems
}
You can use with style like this:
let leftButtonItem = UIBarButtonItem(image: UIImage(named: "ic_top_back"), style: .Plain, target: self, action: "onBackButtonClicked:")
addCustomNavigationItemAtLeftAndRightSide([leftButtonItem], rightButtonItems: [])

How to change the icon of a Bar Button when pressed in Swift?

I'm creating a stopwatch in Swift and I want to change the play icon I have selected for a bar button to a pause icon when the button is pressed to start the stopwatch. How do you do this?
You can not change a UIBarButtonItem's style during runtime. You must remove the UIBarButtonItem and then add the UIBarButtonItem you'd like.
#IBOutlet weak var toolBar: UIToolbar!
var pauseButton = UIBarButtonItem()
var playButton = UIBarButtonItem()
var arrayOfButtons = [AnyObject]()
override func viewDidLoad() {
super.viewDidLoad()
pauseButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Pause, target: self, action: "pauseButtonTapped")
playButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Play, target: self, action: "playButtonTapped")
arrayOfButtons = self.toolBar.items!
arrayOfButtons.insert(playButton, atIndex: 0) // change index to wherever you'd like the button
self.toolBar.setItems(arrayOfButtons, animated: false)
}
func playButtonTapped() {
arrayOfButtons = self.toolBar.items!
arrayOfButtons.removeAtIndex(0) // change index to correspond to where your button is
arrayOfButtons.insert(pauseButton, atIndex: 0)
self.toolBar.setItems(arrayOfButtons, animated: false)
}
func pauseButtonTapped() {
arrayOfButtons = self.toolBar.items!
arrayOfButtons.removeAtIndex(0) // change index to correspond to where your button is
arrayOfButtons.insert(playButton, atIndex: 0)
self.toolBar.setItems(arrayOfButtons, animated: false)
}
UIBarButtonItem Class Reference
For Swift 3
This is how I did it in Swift 3:
var favoritesBarButtonOn: UIBarButtonItem!
var favoritesBarButtonOFF: UIBarButtonItem!
favoritesBarButtonOn = UIBarButtonItem(image: #imageLiteral(resourceName: "TabBarIconSettingsOff"), style: .plain, target: self, action: #selector(didTapFavoritesBarButtonOn))
favoritesBarButtonOFF = UIBarButtonItem(image: #imageLiteral(resourceName: "TabBarIconSettingsOn"), style: .plain, target: self, action: #selector(didTapFavoritesBarButtonOFF))
self.navigationItem.rightBarButtonItems = [self.rightNavBarButton, self.favoritesBarButtonOn]
func didTapFavoritesBarButtonOn() {
self.navigationItem.setRightBarButtonItems([self.rightNavBarButton, self.favoritesBarButtonOFF], animated: false)
print("Show Favorites")
}
func didTapFavoritesBarButtonOFF() {
self.navigationItem.setRightBarButtonItems([self.rightNavBarButton, self.favoritesBarButtonOn], animated: false)
print("Show All Chat Rooms")
}
For Swift 4
var favoritesBarButtonOn: UIBarButtonItem!
var favoritesBarButtonOFF: UIBarButtonItem!
favoritesBarButtonOn = UIBarButtonItem(image: #imageLiteral(resourceName: "TabBarIconSettingsOff"), style: .plain, target: self, action: #selector(didTapFavoritesBarButtonOn))
favoritesBarButtonOFF = UIBarButtonItem(image: #imageLiteral(resourceName: "TabBarIconSettingsOn"), style: .plain, target: self, action: #selector(didTapFavoritesBarButtonOFF))
self.navigationItem.rightBarButtonItems = [self.favoritesBarButtonOn]
func didTapFavoritesBarButtonOn() {
self.navigationItem.setRightBarButtonItems([self.favoritesBarButtonOFF], animated: false)
print("Show Favorites")
}
func didTapFavoritesBarButtonOFF() {
self.navigationItem.setRightBarButtonItems([self.favoritesBarButtonOn], animated: false)
print("Show All Chat Rooms")
}
I believe that you already found a solution for your question, but I'll leave this in case anyone still needs it.
UIBarButtonItem is not a UIControl, however you can initialise it with a custom view, i.e. a custom UIButton programmatically as follows:
let playButton = UIButton(frame: CGRectMake(0, 0, 30, 30))
playButton.addTarget(self, action: "togglePlay:", forControlEvents: .TouchUpInside)
playButton.setImage(UIImage(named: "play-active"), forState: .Normal)
playButton.setImage(UIImage(named: "play-inactive"), forState: .Selected)
let rightButton = UIBarButtonItem(customView: playButton)
self.navigationItem.setRightBarButtonItems([rightButton], animated: true)
idea from Custom "Pressed" UIBarButtonItem Backgrounds

How to change the bar button icon in toolbar in swift?

I am trying to toggle between the play button and pause button in swift. I have a bar button item in the toolbar whose identifier is initially set to the play. I tried to search and found out the following piece of code but it does not work, looks like it works when the bar button is in the navigation bar
self.navigationItem.setLeftBarButtonItem(UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Play, target: self, action: "TheMethodThatTheButtonShouldCall"), animated: true)
You need to set items on UIToolbar to update toolbar items: call func setItems(_items: [AnyObject]?,animated animated: Bool) with your new items to update the toolbar's items
Source: https://developer.apple.com/library/prerelease/ios/documentation/UIKit/Reference/UIToolbar_Class/index.html#//apple_ref/occ/instm/UIToolbar/setItems:animated:
Implemented your question with the code as below. works in Swift 2. Please note I connected the IBAction outlet to playBtn
import UIKit
import AVFoundation
class ViewController: UIViewController {
#IBOutlet var sliderVal: UISlider!
#IBOutlet var theToolbar: UIToolbar!
var mySound = AVAudioPlayer()
override func viewDidLoad() {
super.viewDidLoad()
let path = NSBundle.mainBundle().pathForResource("ColdPlay", ofType: "mp3")
do {
mySound = try AVAudioPlayer(contentsOfURL: NSURL(fileURLWithPath: path!))
}
catch{
print("error caught")
}
}
#IBAction func playBtn(sender: UIBarButtonItem) {
let theBarbuttonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Pause, target: self, action: "pauseBtn:")
let arrayBarButtonItem = [theBarbuttonItem]
theToolbar.setItems(arrayBarButtonItem, animated: true)
mySound.play()
}
#IBAction func pauseBtn(sender: UIBarButtonItem) {
let theBarbuttonItemB = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Play, target: self, action: "playBtn:")
let arrayBarButtonItemB = [theBarbuttonItemB]
theToolbar.setItems(arrayBarButtonItemB, animated: true)
mySound.pause()
}
}

Swift: change Bar Button Item in code

I am using swift. I have a Bar Button Item that I would like to change the Identifier from Play to Stop in code. Is this possible and how do you do It?
#IBOutlet var StartStopButton: UIBarButtonItem!
#IBAction func StartAlarm(sender: AnyObject) {
onOffIndicator.hidden = false
StartStopButton.Identifier = ?????
}
Unfortunately you can't change the identifier so you have to set the whole bar button item. You have to do the following:
self.navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .Stop, target: self, action: "startAlarm:")
To make it nicer you can define an array of UIBarButtonSystemItems and an index like so:
let myArray = [UIBarButtonSystemItem.Start, UIBarButtonSystemItem.Stop]
var index = 0
Then you can do:
self.navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: myArray[++index % myArray.count], target: self, action: "startAlarm:")
By the way, remember to use non-capitalized function and variable names ;)
Swift 5
#IBOutlet var StartStopButton: UIBarButtonItem!
#IBAction func StartAlarm(sender: AnyObject) {
onOffIndicator = !onOffIndicator
if onOffIndicator {
StartStopButton.image = UIImage(systemName: "stop")
} else {
StartStopButton.image = UIImage(systemName: "play")
}
}

Resources