Navigating between UIViewControllers, retaining selected button image - ios

How would you save a selected button state after you press it? So when you switch between view controllers and come to the original view controller, the button stays pressed, until you press it again...
- (void)viewDidLoad
{
[super viewDidLoad];
addCheck = NO;
favCheck = NO;
}
- (IBAction)listButton:(id)sender {
UIImage *removeListImage = [UIImage imageNamed:#"removeList.png"];
UIImage *addListImage = [UIImage imageNamed:#"addList.png"];
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSMutableArray *favoriteviews = [defaults mutableArrayValueForKey:#"favorite_views_key"];
[defaults setObject:favoriteviews forKey:#"favorite_views_key"];
[defaults synchronize];
if (!addCheck) {
[addList setImage:removeListImage forState:UIControlStateNormal];
addCheck = YES;
[favoriteviews addObject:#"Apple"];
[favoriteviews addObject:#"Banana"];
[favoriteviews addObject:#"Celery"];
}
else if (addCheck) {
[addList setImage:addListImage forState:UIControlStateNormal];
addCheck = NO;
[favoriteviews removeObject:#"Apple"];
[favoriteviews removeObject:#"Banana"];
[favoriteviews removeObject:#"Celery"];
}
}

For the simplest cases, you can set the images for two different states of the control(button in this case).
And check for the states on each tap to change it. For example
if(![myButton isSelected]){
[myButton setSelected:YES];
// Do your proceedings when the button is selected here
}
else{
[myButton setSelected:NO];
// Do your proceedings when the button is unselected here
}
And when you set up your button in viewDidLoad, just set the button's images for those two states
[addList setImage:addListImage forState:UIControlStateNormal];
[addList setImage:removeListImage forState:UIControlStateSelected];
Alternatively, if you are setting up button in Interface builder, you can set those images for the two states there too.
It would be better add some logic to it to persist some kind of data to set the button's state depending upon that.

Related

Dynamic Radio Button in Objective C

I want to design a dynamic radio button in my app
for (int f = 0; f<arr.count; f++) {
UILabel *lbl = [[UILabel alloc]init];
lbl.frame = CGRectMake(radio_x+10,radio_y+5 , radio_w, radio_h);
lbl.text = arr[f];
lbl.textColor = [UIColor blackColor];
[self.sub_View addSubview:lbl];
self.yourButton = [[UIButton alloc] initWithFrame:CGRectMake(xPosOfTxt,radio_y , 20, 20)];
[self.yourButton setImage: [UIImage imageNamed:#"RadioButton-Selected.png"]forState:UIControlStateNormal];
[self.yourButton setImage: [UIImage imageNamed:#"RadioButton-Unselected.png"]forState: UIControlStateSelected];
[self.yourButton setTag:baseRadioTag+f];
[self.sub_View addSubview:self.yourButton];
[self.yourButton addTarget:self action:#selector(radioSelected:) forControlEvents:UIControlEventTouchUpInside];
}
-(void)radioSelected:(UIButton*)sender {
self.yourButton.selected = false;
sender.selected = !sender.selected;
self.yourButton = sender; }
I did like this , this is working like , selecting all the options , i want to select only one option at once , if I selected option 1 -> option 2 should be unselected . If I selected option 2 -> option 1 should be deselected.Please help me to do this .
First of all to make things easier
create a array which can hold reference of all the buttons
#interface ViewController ()
{
NSMutableArray *btnArray;
}
Create an object of Array
- (void)viewDidLoad {
[super viewDidLoad];
btnArray = [NSMutableArray new];
/// Here is your code for creating buttons
}
Now add all created buttons to this array
// this is last line from your code where you create your UI
[self.yourButton addTarget:self action:#selector(radioSelected:) forControlEvents:UIControlEventTouchUpInside];
// add this line to add your button to array
[btnArray addObject:self.yourButton];
}
Now when you click button radioSelected method is called
NOTE -: Here can be two cases according to me, but i don't know which one you require so i am explaining both of them
CASE FIRST :-When you select or deselect buttons final output can be that there can be no button selected(all can be deselected)
-(void)radioSelected:(UIButton*)sender{
// here if button is selected, deselect it otherwise select it
[sender setSelected:!sender.isSelected];
for (UIButton* btn in btnArray) {
// here we mark all other button as deselected except the current button
if(btn.tag != sender.tag){
// here when you deselect all button you can add a if statement to check that we have to deselect button only if it is selected
if(btn.isSelected){
[btn setSelected:NO];
}
}
}
}
CASE SECOND:-When atleast one button will be selected
-(void)radioSelected:(UIButton*)sender{
// here if current button is already selected we will not allow to deselect it and return
if(sender.isSelected){
return;
}
// here working is as same as described above
[sender setSelected:!sender.isSelected];
for (UIButton* btn in btnArray) {
if(btn.tag != sender.tag){
[btn setSelected:NO];
}
}
}
You can test both cases and use according to your requirement.
Hope this works for you.
And let me know if you face any issues :)

How to make image on unbutton persist until its not changed by the user .?

I am working on UIButton as a check box, when I press button than checkbox selected image is appear and when press again checkbox unselected image is appear. if I press button image is appear, but it again disappear when I come back to that view again.
- (void)viewDidLoad {
[super viewDidLoad];
_car.delegate = self;
_car.keyboardType = UIKeyboardTypeNumberPad;
[_PreCheck setBackgroundImage:[UIImage imageNamed:#"checkbx_unchecked#2x.png"] forState:UIControlStateNormal];
[_PreCheck setBackgroundImage:[UIImage imageNamed:#"checkbx#2x.png"] forState:UIControlStateSelected];
[_PreCheck addTarget:self action:#selector(checkboxSelected:) forControlEvents:UIControlEventTouchUpInside];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}
-(void)checkboxSelected:(id)sender
{
if ((checkBoxSelected = !checkBoxSelected)) {
[_PreCheck setSelected:checkBoxSelected];
NSLog(#"selected");
NSString *selected = #"selected";
NSUserDefaults *select = [NSUserDefaults standardUserDefaults];
[select setObject:selected forKey:#"checkboxselected"];
[select synchronize];
}
else
{
NSLog(#"not selected");
[_PreCheck setSelected:notselected];
}
}
Based on your posted code your ViewDidLoad must be check with current NSUserDefaults store value is selected or not based on it first you need to set button check uncheck image. so following is your viewDidLoad Code look like:
- (void)viewDidLoad {
[super viewDidLoad];
_car.delegate = self;
_car.keyboardType = UIKeyboardTypeNumberPad;
NSString *state = [[NSUserDefaults standardUserDefaults] stringForKey:#"btnstate"];
if([state isEqualToString:#"selected"])
{
[_PreCheck setBackgroundImage:[UIImage imageNamed:#"checkbx#2x.png"] forState:UIControlStateNormal];
[_PreCheck setSelected:YES];
}
else
{
[_PreCheck setBackgroundImage:[UIImage imageNamed:"checkbx_unchecked#2x.png"] forState:UIControlStateNormal];
[_PreCheck setSelected:NO];
}
[_PreCheck addTarget:self action:#selector(checkboxSelected:) forControlEvents:UIControlEventTouchUpInside];
}
Now set the method for check-uncheck like following:
-(void)checkboxSelected:(UIButton*)sender
{
sender.selected = !sender.selected;
if([sender isSelected])
{
[_PreCheck setBackgroundImage:[UIImage imageNamed:#"checkbx#2x.png"] forState:UIControlStateNormal];
[[NSUserDefaults standardUserDefaults] setValue:#"selected" forKey:#"btnstate"];
}
else
{
[_PreCheck setBackgroundImage:[UIImage im ageNamed:#"checkbx_unchecked#2x.png"] forState:UIControlStateNormal];
[[NSUserDefaults standardUserDefaults] setValue:#"notselected" forKey:#"btnstate"];
}
}
Hope that work or you. just replace your code with my posted code no need to do other changes.
Store the button state in NSUSerDefaults.
Then In viewDidLoad get the state and based on that load image.
- (void)viewDidLoad
{
// Your code
// get selected state from user defaults.
BOOL selected = [[NSUserDefaults standardUserDefaults] boolForKey:#"buttonstateKey"];
if (selected)
{
// set selected image
}
else
{
// set regular image
}
}

How when Button pressed twice the color should change using NSUSerDefaults

I am new to XCode. I used with NSUserDefaults even though it is not coming what i required means If i click one time on that button it should change the colour to green and if i press it again it should change the colour to black.
Here my Code is -
- (IBAction)subscribeButtonAction:(id)sender {
if (count == 0) {
[_subscribeButtonObj setBackgroundColor:[UIColor greenColor]];
greenStr=[NSString stringWithFormat:#"green"];
NSUserDefaults *greendefults=[NSUserDefaults standardUserDefaults];
[greendefults setValue:greenStr forKey:#"greencolor"];
[greendefults synchronize];
///
count++;
} else if(count == 1){
[_subscribeButtonObj setBackgroundColor:[UIColor blueColor]];
blackStr=[NSString stringWithFormat:#"black"];
NSUserDefaults *blackDefaults=[NSUserDefaults standardUserDefaults];
[blackDefaults setValue:blackStr forKey:#"blackcolor"];
[blackDefaults synchronize];
//count = 0;
}
}
In ViewWillAppear I wrote the code like this -
-(void)viewWillAppear:(BOOL)animated
{
//count = 0;
if ([[NSUserDefaults standardUserDefaults] stringForKey:#"greencolor"]) {
NSLog(#"change the button to green color %#",[[NSUserDefaults standardUserDefaults] stringForKey:#"greencolor"]);
} else {
NSLog(#"change the button to blackcolor ");
}
}
Can anyone please help me. Thanks in Advance
There's no need of NSUserDefaults to implement this. Its simple to handle with UIButton's control states,
UIControlStateNormal
UIControlStateSelected
For example,
- (IBAction)changeColor:(id)sender {
UIButton *button = (UIButton *)sender;
if (button.selected) { // If selected will change the color into Red
button.backgroundColor = [UIColor redColor];
[button setSelected:NO];
} else {
button.backgroundColor = [UIColor greenColor];
[button setSelected:YES];
}
}
And, keeep in mind you can change your button's state initially like setting this,
[myButton setSelected:YES];
Assign, this code in your viewDidLoad
Cheers!!
If you wanna do it the NSUserDefault way. Setting control states is a nice way though. but It will set a unwanted overlay background to the button if UIControlStateSelected is YES. :
- (IBAction)btnAction:(id)sender {
NSUserDefaults *color=[NSUserDefaults standardUserDefaults];
if (count == 0) {
[self.btnOutlet setBackgroundColor:[UIColor greenColor]];
[color setValue:#"green" forKey:#"color"];
}else if(count == 1){
[self.btnOutlet setBackgroundColor:[UIColor blueColor]];
[color setValue:#"blue" forKey:#"color"];
}
count = !count;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
count = 0;
if([[[NSUserDefaults standardUserDefaults] valueForKey:#"color"] isEqualToString:#"green"]){ // been used
[self.btnOutlet setBackgroundColor:[UIColor greenColor]];
}else if([[[NSUserDefaults standardUserDefaults] valueForKey:#"color"] isEqualToString:#"blue"]){
[self.btnOutlet setBackgroundColor:[UIColor blueColor]];
}else{ // first time
[self.btnOutlet setBackgroundColor:[UIColor yellowColor]];
}
}

Determine if view is hidden or not and change button state programmatically

I have three views and three buttons each button toggles the view (hidden = yes/no)
- (IBAction)switchOne:(id)sender {
[_firstPage setHidden:NO];
[_secondPage setHidden:YES];
[_thirdPage setHidden:YES];
}
- (IBAction)switchTwo:(id)sender {
[_firstPage setHidden:YES];
[_secondPage setHidden:NO];
[_thirdPage setHidden:YES];
}
- (IBAction)switchThree:(id)sender {
[_firstPage setHidden:YES];
[_secondPage setHidden:YES];
[_thirdPage setHidden:NO];
}
I want to set the background of the button depending if the view is hidden or not.
I have tried this but without results:
if (_firstPage.hidden == NO)
{
UIImage *buttonImage = [UIImage imageNamed:#"currentPage.png"];
[_pageOneButton setBackgroundImage:buttonImage forState:UIControlStateNormal];
[self.view addSubview:_pageOneButton];
} else if (_firstPage.hidden == YES) {
[_pageOneButton setBackgroundImage:nil forState:UIControlStateNormal];
}
The _pageOneButton keeps the background even with the view hidden.
I leave an image of the menu as is now:
The point is: when Página 2 is active (hidden == NO) the Página 1 button should be without the background.
To few details here, but in the meantime you could play a bit with the following suggestions.
First, move your
[self.view addSubview:_pageOneButton];
outside the method. For example, in viewDidLoad method you add that button to a superview.
Then you can control its state (through a reference to it, as you did) like
// set the image
[_pageOneButton setImage:image forState:UIControlStateNormal];
// remove the image
[_pageOneButton setImage:nil forState:UIControlStateNormal];

Changing a UIButton to be turned off

I have a simple button with two images for each UIControlStates.
I want this button to behave as a control and as indicator so that I can press it down - "activate" and press again "deactivate", While some other functions can cause it to be turned off ("deactivate").
My question is how can I change it's state from selected to not-selected?
Changing the selected property would not do the trick :)
You can disable the button so it can't be press able.
yourButton.enabled = NO;
and When you want it back to be press able, then you can enabled it
yourButton.enabled = YES;
Simplest way would be consider button as switch and change it's state according switch on/off. For example use BOOL variable which upon button touch gets its value YES or NO while according to it button gets its image.
- (void) buttonTouched:(id)sender
{
switchOn = !switchOn;
UIImage *buttonImage = nil;
if (switchOn == YES)
{
buttonImage = [UIImage imageNamed:#"on.png"];
}
else
{
buttonImage = [UIImage imageNamed:#"off.png"];
}
[myButton setImage:buttonImage forState:UIControlStateNormal];
[myButton setImage:buttonImage forState:UIControlStateSelected];
}
if you need to programmatically set button "disabled":
- (void) setButtonDisabled
{
switchOn = YES; //calling buttonTouched: will turn it to NO
[self buttonTouched:nil];
}

Resources