Change BarButtonItem icon on click - ios

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: [])

Related

UIButtonBarItem not changing

I have a bottom toolbar in an iOS app the only contains one button to play / pause a live Icecast radio stream. Everything is working except the button changing from the Play icon to the Pause icon and vice versa. Here's my code.
#IBAction func PlayStop(_ sender: Any) {
if player.timeControlStatus == .playing {
// Stop the live radio stream
player.pause()
// Set the radio tower image to off with Alpha 0.3
TowerImage.image = UIImage(named: "TowerOff")
TowerImage.alpha = 0.3
// Set the Toolbar icon to the Play Icon
PlayStopButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonItem.SystemItem.play, target: self, action: #selector(ViewController.PlayStop(_:)))
} else if player.timeControlStatus != .playing {
// Play the live radio stream
player.play()
// Set the radio tower image to on with Alpha 1
TowerImage.image = UIImage(named: "TowerOn")
TowerImage.alpha = 1
// Set the Toolbar icon to the Pause Icon
PlayStopButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonItem.SystemItem.pause, target: self, action: #selector(ViewController.PlayStop(_:)))
}
}
#IBOutlet var TowerImage: UIImageView!
#IBOutlet var PlayStopButton: UIBarButtonItem!
You want to hook the toolbar as outlet then
let playStopButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonItem.SystemItem.pause, target: self, action: #selector(ViewController.PlayStop(_:)))
self.toolBar.items = [playStopButton]

Trying to make rightBarButton appear after making it disappear using Swift

I currently am working on an app in Swift where in my viewDidLoad() method I have purposely hidden my rightBarButton on my navigation bar like this:
self.navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .Done, target: self, action: #selector(TableViewController.dismiss))
self.navigationItem.setRightBarButtonItem(nil, animated: true)
However, under certain circumstances, I would like to display the rightBarButton. How would I do this? What would be the opposite of the above line of code?
Once you set the bar button item to nil, it is gone. Something you can do however, is store the bar button item like so:
let barButtonItem = UIBarButtonItem(barButtonSystemItem: .Done, target: self, action: #selector(TableViewController.dismiss));
and then you can make it appear/disappear like so:
self.navigationItem.rightBarButtonItem = barButtonItem
self.navigationItem.setRightBarButtonItem(nil, animated: true)
then just access the barButtonItem whenever you want it to appear/disappear.
You can do one of the following two options:
Keep a reference of your UIBarButtonItem and every time you disappear you save it to then when you want to show it again you set the old value.
Play with the color of the UIBarButtonItem and the enabled/disable property to enable the interaction with it.
The first choice always keep a reference globally to the UIBarButtonItem and the second need to know the exact color of the original UIBarButtonItem to give to its original state:
First Option:
private var isHidden: Bool!
private var righBarButtonItem: UIBarButtonItem!
#IBAction func hideButton(sender: AnyObject) {
if self.isHidden == true {
self.isHidden = false
self.navigationItem.rightBarButtonItem = righBarButtonItem
}
else {
self.isHidden = true
righBarButtonItem = self.navigationItem.rightBarButtonItem
self.navigationItem.setRightBarButtonItem(nil, animated: true)
}
}
Second Option:
#IBAction func hideButton(sender: AnyObject) {
if self.isHidden == true {
self.isHidden = false
self.navigationItem.rightBarButtonItem?.tintColor = UIColor.clearColor()
self.navigationItem.rightBarButtonItem?.enabled = false
}
else {
self.isHidden = true
self.navigationItem.rightBarButtonItem?.tintColor = UIColor.blueColor()
self.navigationItem.rightBarButtonItem?.enabled = true
}
}
In the above examples I set a variable with the state of the UIBarButtonItem for purposes of know the value and and #IBOutlet to hide/show the UIBarButtonItem. The variable isHidden need to set it's initial value in the viewDidLoad.
I hope this help you.

Change bar button Item from Play to Pause Swift

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
}

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

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