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]
Related
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.
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: [])
I have a UIBarButton saveBarButton to save an image of the screen to the camera roll. When the user presses the saveBarButton the image is saved and the UIBarButton saveBarButton changes to the UIImage doneIconfor 1.2 seconds to indicate to the user that the image has been saved. When the saveBarButton displays the doneIcon I disable saveBarButton. However, when I do that the saveBarButton is greyed out.
My question is: how do I stop the UIBarButton from greying out when disabled?
My code:
//create UIBarButton saveBarButton
override func viewDidLoad() {
let saveBarButton = UIBarButtonItem(image: UIImage(named: "saveIcon"), style: .Plain, target: self, action: "save:")
saveBarButton.tintColor = colorGreyDark
}
//save function called when press saveBarButton
func save(sender: UIBarButtonItem) {
//save image
deselectShape()
let window: UIWindow! = UIApplication.sharedApplication().keyWindow
let windowImage = capture(window)
UIImageWriteToSavedPhotosAlbum(windowImage
, nil, nil, nil)
//Change saveBarButton to indicate to user that image was saved
sender.image = UIImage(named: "doneIcon")
sender.enabled = false //disable saveBarButton
self.performSelector("canSaveAgain:", withObject: sender, afterDelay: 1.2)
}
//Change saveBarButton to original icon to indicate to user that can save another image
func canSaveAgain(sender: UIBarButtonItem){
sender.image = UIImage(named: "saveIcon")
sender.enabled = true //enable saveBarButton
}
To see what I'm talking about.
One of ways is to create UIBarButtonItem with customView and use userInteractionEnabled instead enabled.
let saveBarButton = UIBarButtonItem(customView: saveButton)
saveBarButton.customView?.userInteractionEnabled = false
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
}
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")
}
}