I'm starting to create a favorite button for my project and i need some help...
I have created a button and already programmed it to switch image when tapped right here:
override func viewDidLoad() {
super.viewDidLoad()
//create a new button
let Favoritebutton: UIButton = UIButton(type: UIButtonType.Custom)
//set image for button
Favoritebutton.setImage(UIImage(named: "EmptyHeart.png"), forState: UIControlState.Normal)
Favoritebutton.setImage(UIImage(named: "FilledHeart.png"), forState: UIControlState.Selected)
//add function for button
Favoritebutton.addTarget(self, action: #selector(self.button(_:)), forControlEvents: .TouchUpInside)
//set frame
Favoritebutton.frame = CGRectMake(90, 90, 35, 35)
let barButton = UIBarButtonItem(customView: Favoritebutton)
//assign button to navigationbar
self.navigationItem.rightBarButtonItem = barButton
}
#IBAction func button(sender: UIButton) {
sender.selected = !sender.selected;
}
It works perfectly but as of right now if i quit the app the button does NOT save the status if its selected or not . I heard you can achieve this with NSUserDefault but i don't know how to implement this so i would love to get some help with it :)
I am using Swift 2.3 and Xcode 8.
Thank you.
It's quite easy. In UserDefaults you can store boolean value without any problem.
In viewDidLoad you check value for your key like this.
let defaults = UserDefaults.standard
let buttonIsSelected = defaults.bool(forKey: "keyForIsButtonSelected") // If no value exists for this key then false is returned
button.selected = buttonIsSelected
Inside your button function remember to save your status.
sender.selected = !sender.selected
let defaults = UserDefaults.standard
defaults.set(sender.selected, forKey: "keyForIsButtonSelected")
defaults.synchronize() // Save your defaults, can also move this part of code to applicationWillTerminate
For Swift 2.3 use this.
let defaults = NSUserDefaults.standardUserDefaults()
let buttonIsSelected = defaults.boolForKey("keyForIsButtonSelected") // If no value exists for this key then false is returned
button.selected = buttonIsSelected
Inside button function.
sender.selected = !sender.selected
let defaults = NSUserDefaults.standardUserDefaults()
defaults.setBool(sender.selected, forKey: "keyForIsButtonSelected")
defaults.synchronize() // Save your defaults, can also move this part of code to applicationWillTerminate
for swift 3 it will be next:
//save value
UserDefaults.standard.set(selected, forKey: "lButtonSelected")
//then on next launch restore it
let selected = UserDefaults.standard.value(forKey: "lButtonSelected")
To save the value in NSUserDefaults:
UserDefaults.standard.set(selected, forKey: "buttonStatus")
UserDefaults.standard.synchronize()
And to retrieve the value from NSUserDefaults:
let buttonStatus = UserDefaults.standard.value(forKey: "buttonStatus")
Related
I have a TabBar Application and I'm trying to set up a favorites tab.
I have managed to create a button and to send the favorited cell to the tab but right now if i add to favorites they are added correctly into the favorites tab but if i quit the app it doesn't save the favorites . How can i save the favorited cells in the favorite tab? would UserDefault do the best job? and if so how can it be done...
This is how i set up my favorite button :
//create a new button
let Favoritebutton: UIButton = UIButton(type: UIButtonType.custom)
//set image for button
Favoritebutton.setImage(UIImage(named: "EmptyHeart.png"), for: .normal)
Favoritebutton.setImage(UIImage(named: "FilledHeart.png"), for: .selected)
//add function for button
Favoritebutton.addTarget(self, action: #selector(self.button), for: .touchUpInside)
//set frame
Favoritebutton.frame = CGRect(x:0,y: 0,width: 35,height: 35)
Favoritebutton.isSelected = UserDefaults.standard.bool(forKey: "isSaved")
let barButton = UIBarButtonItem(customView: Favoritebutton)
//assign button to navigationbar
self.navigationItem.rightBarButtonItem = barButton
}
#IBAction func button(sender: UIButton) {
let newValue = !sender.isSelected
sender.isSelected = newValue
UserDefaults.standard.set(newValue, forKey: "isSaved")
let tabItem = self.tabBarController?.tabBar.items![3]
sel_val = tabItem?.badgeValue
if(sel_val == nil){
sel_val = "0"
}
let sel_num = Int(sel_val!)
let fav: NSMutableArray = []
fav.add(barImage)
fav.add(barName)
fav.add(streetName)
if sender.isSelected {
tabItem!.badgeValue = String(format: "%d", sel_num! + 1)
favorite.add(fav)
} else {
tabItem!.badgeValue = String(format: "%d", sel_num! - 1)
favorite.remove(fav)
}
}
#Newbie - I think you are not checking, second time when app open what is your favourite tab with your NSUserDefault.
I'm trying to complete my favorite button by saving it state even when i quit the view \ App . it will be great if anyone could show me how can i do this, I'm using Xcode 8 and coding with Swift 3.
Current Button Code :
//create a new button
let Favoritebutton: UIButton = UIButton(type: UIButtonType.custom)
//set image for button
Favoritebutton.setImage(UIImage(named: "EmptyHeart.png"), for: .normal)
Favoritebutton.setImage(UIImage(named: "FilledHeart.png"), for: .selected)
//add function for button
Favoritebutton.addTarget(self, action: #selector(self.button), for: .touchUpInside)
//set frame
Favoritebutton.frame = CGRect(x:0,y: 0,width: 35,height: 35)
let barButton = UIBarButtonItem(customView: Favoritebutton)
//assign button to navigationbar
self.navigationItem.rightBarButtonItem = barButton
let state = UserDefaults.standard.bool(forKey: "isSaved") ?? false
}
#IBAction func button(sender: UIButton) {
sender.isSelected = !sender.isSelected
UserDefaults.standard.set(true,forKey: "isSaved")
UserDefaults.standard.synchronize()
if let Favoritebutton = sender as? UIButton {
if Favoritebutton.isSelected {
// set selected
Favoritebutton.isSelected = true
UserDefaults.standard.set(true, forKey: "MY_FAV_KEY")
UserDefaults.standard.synchronize()
// set badge to tabbar item.
let tabItem = self.tabBarController?.tabBar.items![3]
sel_val = tabItem?.badgeValue
if(sel_val == nil){
sel_val = "0"
}
let sel_num = Int(sel_val!)
tabItem!.badgeValue = String(format: "%d", sel_num! + 1) as String
let Fav: NSMutableArray = []
Fav.add(barImage)
Fav.add(barName)
Fav.add(streetName)
favorite.add(Fav)
} else {
// set deselected
Favoritebutton.isSelected = false
UserDefaults.standard.set(true, forKey: "MY_FAV_KEY")
UserDefaults.standard.synchronize()
let tabItem = self.tabBarController?.tabBar.items![3]
sel_val = tabItem?.badgeValue
if(sel_val == nil){
sel_val = "0"
}
let sel_num = Int(sel_val!)
tabItem!.badgeValue = String(format: "%d", sel_num! - 1) as String
let Fav: NSMutableArray = []
Fav.add(barImage)
Fav.add(barName)
Fav.add(streetName)
favorite.remove(Fav)
}
}
As i said,It will be great if anyone could help me save the button's state
even if i quit the view or app , i would really appreciate it, Thank you in advance !
Saving the value to UserDefaults writes it out to the plist file. It does not read the value back in or restore state when the app resumes. You are responsible for that. So somewhere in viewDidLoad check the state:
let state = UserDefaults.standard.bool(forKey: "isSaved") ?? false
Then set your button accordingly
I have added a UISwitch to my Navigation Controller. This switch controls the underlying tableview and toggles it between 2 data sources. However, when i tried adding IBOutlets and Actions the suggested type came up as UIBarButtonItem, nevertheless when i saved it as a UISwitch, so i could have the .on boolean. However, it seems that the switch is not doing anything. When i click it nothing is happening and Im not sure as to why. My code below.
#IBAction func PreferencesToggled(sender: UIButton) {
if DataToggle.on
{
let defaults = NSUserDefaults.standardUserDefaults()
if let prefs = defaults.objectForKey("teachPref"){
data = prefs as! [newsarticle]
self.tableView.reloadData()
}
else{
data = [newsarticle]()
data.append(newsarticle(name: "No Teachers Saved",desc: "http://www.google.com"))
}
let footer = UIView()
self.tableView.tableFooterView = footer
}
else{
self.tableView.tableFooterView = nil
getdata()
}
}
This is how to add a switch programmatically to your navigtion bar:
let switchView = UISwitch()
switchView.addTarget(self, action: #selector(self.PreferencesToggled(_:)), forControlEvents: .ValueChanged)
//customize your switch here
let barBtn = UIBarButtonItem(customView: switchView)
self.navBar?.topItem?.setRightBarButtonItem(barBtn, animated: false)
I’m trying to change the image of a button when tapped (it’s for an audio player that I want Play to change to Pause). So far I’ve only managed to change it when the button is held, then it changes back when released.
I’ve tried using Selected instead of Highlighted but that doesn’t work. (The initial image is set in the Attributes Inspector). This is what I have -
#IBAction func buttonTapped(sender: AnyObject) {
ColourTestButton.setImage(UIImage(named: "blank-purple.jpg"), forState:.Highlighted)
}
I realise Highlighted means just that though on another image where I wanted it to change back (in a Cell of a Table View) it stayed, which is why I thought it would work for this one. What do I have to do here to make it stay changed to the new image?
I think you need this code:
#IBAction func buttonTapped(sender: AnyObject) {
let image = UIImage(named: "blank-purple.jpg") as UIImage!
let playButton = UIButton.buttonWithType(UIButtonType.Custom) as! UIButton
ColourTestButton.setImage(image, forState: .Normal)
}
UPDATE:
If you want to change the image like play/pause then you can do it this way:
var pressed = false
#IBAction func pressed(sender: AnyObject) {
if !pressed {
let image = UIImage(named: "pauseImage.png") as UIImage!
let playButton = UIButton.buttonWithType(UIButtonType.Custom) as! UIButton
btn.setImage(image, forState: .Normal)
pressed = true
} else {
let image = UIImage(named: "playImage.png") as UIImage!
let playButton = UIButton.buttonWithType(UIButtonType.Custom) as! UIButton
btn.setImage(image, forState: .Normal)
pressed = false
}
}
I think you are updating the image only at Highlighted state, so when you release the button it goes back to an original image. Try to change it at Normal state so that it will change the image. Take one flag to check the Play and Pause condition.
#IBAction func buttonTapped(sender: AnyObject) {
if (!flag)
{
//for Play
flag = true
ColourTestButton.setImage(UIImage(named:"USE PLAY IMAGE"), forState:. Normal)
}
else
{
//for Pause
flag = false
ColourTestButton.setImage(UIImage(named:"USE PAUSE IMAGE"), forState:. Normal)
}
}
Though Dharmesh Kheni's answer is OK I would recommend to use two buttons. You can set them in separate function or in interface builder and then just show and hide them according to state. Something like this:
func setButtons()
{
playBtn.setImage(UIImage(named: "play.png"), forState:.Normal)
pauseBtn.setImage(UIImage(named: "play.png"), forState:.Normal)
pauseBtn.hidden = true
}
#IBAction func playTapped(sender: AnyObject)
{
playBtn.hidden = true
pauseBtn.hidden = flase
//do other stuff
}
#IBAction func pauseTapped(sender: AnyObject)
{
playBtn.hidden = false
pauseBtn.hidden = true
//do other stuff
}
I have Objective-C working code for six buttons but I don't seem to find how to change the state of a button using Swift. So how do I make the following code work in Swift?
[self.button2 setBackgroundImage:[UIImage imageNamed:#"button2_selected.png"] forState: UIControlStateSelected];
button1.selected = NO;
button2.selected = !button2.selected;
button3.selected = NO;
button4.selected = NO;
button5.selected = NO;
button6.selected = NO;
Check for this:
var var_button_ = UIButton()
var_button_.setBackgroundImage(UIImage(named: "button2_selected.png"), forState: UIControlState.Normal)
var_button_.selected = false
var_button_.selected = !var_button_.selected
//var_button_.selected = true
Thanks
BY JNYJ
// You need to use the true and false for bool value in swift
buttonOutletName.selected = true buttonOutletName.selected = false
// Create IBAction and check button selected or not in swift language.
You can change the button state.
#IBAction func favoriteButtonAction(sender: UIButton) {
// Save Data
sender.selected = !sender.selected;
if (sender.selected)
{
NSLog(" Not Selected");
sender.selected = false
self.setImage(UIImage(named: "checked_checkbox"), forState: .Normal)
}
else
{
NSLog(" Selected");
sender.selected = false
self.setImage(UIImage(named: "unchecked_checkbox"), forState: .Normal)
}
}
Create an outlet and an action for your button
Give 'button_selected' and 'button_not_selected' images for state configs Selected and Default respectively.
Then write the below code in the action,
if button.isSelected {
button.isSelected = false
}
else {
button.isSelected = true
}
I think this is the simplest way
//Method 1
//Create IBAction and check button selected or not...There is no need to set //sender.selected to true or false in the if/else statement.
#IBAction func rememberMe(sender: UIButton) {
sender.selected = !sender.selected
if sender.selected {
self.setImage(UIImage(named: "RememberMe_Checkmark"), forState: .Normal)
} else {
self.setImage(UIImage(named: "No_Checkmark"), forState: .Normal)
}
}
//METHOD 2 With Custom Type from Storyboard
enter image description here
Click on the Image Link to See Sample
From the Storyboard do the following
1) Change the Button type to "Custom"
2) Change the State Config to "Selected"
3) Set the Image to the Checkbox Icon with a checkmark asset
4) Set the Background to the Checkbox Icon without a checkmark asset
//Create and IBAction from the Button and enter this single Line of Code
#IBAction func rememberMe(sender: UIButton) {
sender.selected = !sender.selected
}