How do I change a button's color when pressed and reset to original color when a different button are pressed? - objective-c

I have created buttons dynamically based on array count ,if i pressed it will move to next page .i want to change the background color of the button if it is pressed .i pressed 1st button its background color should changed ,and den if i pressed anyother buttons the first pressed button should get into default color of the button , and the new pressed button's background color should changed ,
please help me to do this ,On button clicked method i have tried like this ,
- (IBAction)btn1Tapped:(id)sender {
UIButton *btn = (UIButton *) sender;
selected = YES;
if (selected) {
[btn setBackgroundColor:[UIColor redColor]];
}
}
and this my button creation code ,
int buttonheight = 30;
int horizontalPadding = 20;
int verticalPadding = 20;
int totalwidth = self.view.frame.size.width;
int x = 10;
int y = 150;
for (int i=0; i<array.count; i++)
{
NSString* titre = [array objectAtIndex:i];
CGSize contstrainedSize = CGSizeMake(200, 40);//The maximum width and height
NSDictionary *attributesDictionary = [NSDictionary dictionaryWithObjectsAndKeys:
[UIFont systemFontOfSize:20.0], NSFontAttributeName,
nil];
CGRect frame = [titre boundingRectWithSize:contstrainedSize options:NSStringDrawingUsesLineFragmentOrigin attributes:attributesDictionary context:nil];
int xpos = x + CGRectGetWidth(frame);
if (xpos > totalwidth) {
y =y +buttonheight+ verticalPadding;
x = 10;
}
UIButton *word= [UIButton buttonWithType:UIButtonTypeRoundedRect];
self.word = word;
NSLog(#"%#", NSStringFromCGRect(frame));
word = [UIButton buttonWithType:UIButtonTypeRoundedRect];
word.frame = CGRectMake(x, y, CGRectGetWidth(frame)+5, CGRectGetHeight(frame));
[word setTitle:titre forState:UIControlStateNormal];
[word setTitle:titre forState:UIControlStateSelected];
word.backgroundColor = [UIColor colorWithRed:30.0/255.0 green:134.0/255.0 blue:255.0/255.0 alpha:1.0];
[word setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[word setTag:i];
[word addTarget:self action:#selector(btn1Tapped:) forControlEvents:UIControlEventTouchUpInside];
word.layer.borderColor = [UIColor blackColor].CGColor;
word.layer.borderWidth = 1.0f;
word.layer.cornerRadius = 5;
[self.view addSubview:word];
x =x+horizontalPadding+CGRectGetWidth(frame);
}

- (IBAction)allBtnSharedTappedevent:(id)sender {
UIButton *btn = (UIButton *) sender;
[btn setBackgroundColor:[UIColor redColor]];
//loop through all your buttons
for(UIView *view in [self.view subviews]){
if([view isKindOfClass:[UIButton class]]){
if(view != btn){
UIButton* btn1 = (UIButton*) view;
[btn1 setBackgroundColor:[UIColor grayColor]];
}
}
}
}

Keep the buttons in an array.
#property (nonatomic, copy, readonly) NSArray<UIButton *> *buttons;
Then in your method that handles the tap, do something like this.
- (IBAction)buttonTapped:(UIButton *)sender {
// Loop through all buttons, clearing the background color
for (UIButton *button in self.buttons) {
button.backgroundColor = [UIColor clearColor];
}
// Set the background color for the selected button
sender.backgroundColor = [UIColor redColor];
}
You should avoid using the tag property of UIView, it will just cause you headaches down the road.

give your button tag number like 1,2,3,4 ... etc
then
- (IBAction)btn1Tapped:(id)sender {
UIButton *btn = (UIButton *) sender;
[btn setBackgroundColor:[UIColor redColor]];
loop through all your buttons
for(int i = 1;i <= total numbers of button; i++){
if(btn.tag != i){
UIButton* btn1 = [myView viewWithTag:i];
[btn1 setBackgroundColor:[UIColor graycolor]];
}
}
}

Related

Highlighting the button with sender tag

I have 7 buttons on my storyboard, I have associated a tag number to each of the button. And all the buttons are hooked up to a single IBAction.
In my action method I have a switch statement like switch ([sender tag])
which run the appropriate action according to the tag. This is all working.
But I want to add a functionality where selected button is highlight and rest of them in normal state.
You can create property with tags:
#property (nonatomic, strong) NSArray *tags;
Somewhere (for example, in viewDidLoad) initialize it with values used in storyboard:
tags = #[#1, #2, #3, #4, #5]
And select buttons using this tags
- (IBAction)buttonPressed:(UIButton *)sender {
for (int i = 0; i < tags.count; i++) {
UIButton *button = [self.view viewWithTag:tags[i]];
button.selected = (button.tag == sender.tag);
}
}
Or you can create IBOutlets for every 7 buttons and create array for it.
array = #[outlet1, ..., outlet7]
And select buttons using outlets
- (IBAction)buttonPressed:(UIButton *)sender {
for (int i = 0; i < array.count; i++) {
UIButton *button = array[i];
button.selected = (button.tag == sender.tag);
}
}
Hope this can give you some idea:
- (void)setupButtons {
for (int i = 0; i < 7; i++) {
CGFloat width = self.view.frame.size.width / 7;
UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(i * width, 100, width, 30)];
[self.view addSubview:button];
button.tag = 1000 + i;
[button setTitle:[NSString stringWithFormat:#"%d", i] forState:UIControlStateNormal];
button.backgroundColor = [UIColor redColor];
[button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[button setTitleColor:[UIColor whiteColor] forState:UIControlStateSelected];
[button addTarget:self action:#selector(buttonClicked:) forControlEvents:UIControlEventTouchDown];
if (i == 0) {
// default first button selected
button.selected = YES;
}
}
}
- (void)buttonClicked:(UIButton *)sender {
for (int i = 0; i < 7; i++) {
UIButton *button = [self.view viewWithTag:(1000+i)];
button.selected = (button.tag == sender.tag);
}
}

UIButton is not setting text

I seem to have a problem in my Objective C iOS app where I am creating multiple buttons depending on the amount of objects in an array. I know Swift, so I replicated the logic into Swift, and it worked. Yet in Objective C, I am unable to see the text of the button (after I remove the for loop) or create multiple buttons. For example, I have an array full of three names. I would like to create a button for each name with the title set to the corresponding name. So far, I have this:
#import "ViewController.h"
#interface ViewController ()
#end
#implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
NSMutableArray *ages = [[NSMutableArray alloc] init];
for (int i = 0; i > 10; i++) {
[ages addObject:[NSString stringWithFormat:#"%i", i]];
}
UIScrollView *scrollView= [[UIScrollView alloc]initWithFrame:self.view.frame];
scrollView.delegate= self;
self.automaticallyAdjustsScrollViewInsets= NO;
scrollView.backgroundColor= [UIColor clearColor];
scrollView.scrollEnabled= YES;
scrollView.userInteractionEnabled= YES;
[scrollView setShowsHorizontalScrollIndicator:NO];
[scrollView setShowsVerticalScrollIndicator:NO];
CGFloat xValue = 0;
for(int x=0; x > ages.count; x++){
UIButton *button= [[UIButton alloc] initWithFrame:CGRectMake(xValue ,0 , 172 ,65)];
UIColor *buttonOutline = [[UIColor redColor] CGColor];
button.layer.borderColor = [buttonOutline CGColor];
button.layer.backgroundColor = [[UIColor clearColor] CGColor];
button.layer.borderWidth = 1.0;
button.layer.cornerRadius = 6.0;
[button.titleLabel setFont:[UIFont fontWithName:#"Helvetica" size:13.0]];
button.titleLabel.text = [ages objectAtIndex:x];
[button addTarget:self action:#selector(test:) forControlEvents:UIControlEventTouchUpInside];
[scrollView addSubview:button];
NSLog(#"Button Added");
xValue = button.frame.size.width + 40;
}
scrollView.contentSize = CGSizeMake(xValue, 65);
[self.view addSubview:scrollView];
}
- (void)test:(UIButton*)sender{
NSLog(#"Clicked %#", sender.titleLabel.text);
}
#end
If anyone sees anything wrong with this code, please point it out!
Thanks,
Arnav K.
I found four problems (there may be others) that stop this working correctly:
1) The for loop bound when setting up the ages array is incorrect.
2) The for loop bound when creating the buttons is incorrect.
3) You are setting the buttonOutline colour incorrectly.
4) xValue is being updated incorrectly.
Here is the viewDidLoad method after the changes have been made:
- (void)viewDidLoad {
[super viewDidLoad];
NSMutableArray *ages = [[NSMutableArray alloc] init];
for (int i = 0; i < 10; i++) { // UPDATED
[ages addObject:[NSString stringWithFormat:#"%i", i]];
}
UIScrollView *scrollView= [[UIScrollView alloc]initWithFrame:self.view.frame];
scrollView.delegate= self;
self.automaticallyAdjustsScrollViewInsets= NO;
scrollView.backgroundColor= [UIColor clearColor];
scrollView.scrollEnabled= YES;
scrollView.userInteractionEnabled= YES;
[scrollView setShowsHorizontalScrollIndicator:NO];
[scrollView setShowsVerticalScrollIndicator:NO];
CGFloat xValue = 0;
for(int x=0; x < ages.count; x++){ // UPDATED
UIButton *button= [[UIButton alloc] initWithFrame:CGRectMake(xValue ,0 , 172 ,65)];
UIColor *buttonOutline = [UIColor redColor]; // UPDATED
button.layer.borderColor = [buttonOutline CGColor];
button.layer.backgroundColor = [[UIColor clearColor] CGColor];
button.layer.borderWidth = 1.0;
button.layer.cornerRadius = 6.0;
[button.titleLabel setFont:[UIFont fontWithName:#"Helvetica" size:13.0]];
button.titleLabel.text = [ages objectAtIndex:x];
[button addTarget:self action:#selector(test:) forControlEvents:UIControlEventTouchUpInside];
[scrollView addSubview:button];
NSLog(#"Button Added");
xValue += button.frame.size.width + 40; // UPDATED
}
scrollView.contentSize = CGSizeMake(xValue, 65);
[self.view addSubview:scrollView];
}
I have marked the four lines I changed with a UPDATED comment so you can compare them to the original.
EDIT
To change the text and text colour use the following:
[button setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
[button setTitle:[ages objectAtIndex:x] forState:UIControlStateNormal];
and remove this:
button.titleLabel.text = [ages objectAtIndex:x];
You need to do this because you can set different text for the different states of the button and this is all handled automatically for you.

Add texfield in runtime in IOS

I want to make an "add" button to add as many textfields as i want in my scroll view.
I did this already
UITextField *text=[[UITextField alloc]initWithFrame:CGRectMake(50,50,200,200)];
[self.scrollView addSubview:text];
But is not working.
Thanks!
If this is your complete button code:
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[button setTitle:#"Show View" forState:UIControlStateNormal];
button.frame = CGRectMake(80.0, 210.0, 160.0, 40.0);
// add this
[button addTarget:self action:#selector(buttonPressed:) forControlEvents:UIControlEventTouchUpInside];
// continue
[self.mainScroll addSubview:button];
Then add this somewhere:
- (void) buttonPressed:(UIButton *)button {
UITextField *text=[[UITextField alloc]initWithFrame:CGRectMake(50,50,200,200)];
text.backgroundColor = [UIColor greenColor]; // just to make sure it's showing up.
[self.scrollView addSubview:text];
}
First create common function like this,
-(void)setTextfieldStyle:(UITextField *)pTmpTextField
{
pTmpTextField.borderStyle = UITextBorderStyleRoundedRect;
pTmpTextField.font = [UIFont systemFontOfSize:15];
pTmpTextField.placeholder = #"First Name";
pTmpTextField.autocorrectionType = UITextAutocorrectionTypeNo;
pTmpTextField.keyboardType = UIKeyboardTypeDefault;
pTmpTextField.returnKeyType = UIReturnKeyDone;
pTmpTextField.clearButtonMode = UITextFieldViewModeWhileEditing;
pTmpTextField.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
pTmpTextField.delegate = self;
}
and use this for creating UITextFiled,
int y = 0;
for(int i=0;i < 5;i++)
{
UITextField *txtTemp=[[UITextField alloc]initWithFrame:CGRectMake(0, y, 300, 31)];
txtTemp.tag = i;
[self setTextfieldStyle:txtTemp];
[self.view addSubview:txtTemp];
[txtTemp release];
y+=36;
}
This is UITextField's delegate method,
- (void)textFieldDidBeginEditing:(UITextField *)textField
{
NSLog(#"%#",textField.text);
}
Hope this works for you as this works for me. only keep this in mind that add the text fields to your scroll view.
In the example am adding them to my view!

how to add background color to UIbuttons crested by using for loop based on frame sizes?

I have created 5 buttons using for loop based on incrementing y axis value in CGRectMake. But how can i change the background color of button when i clicked each button?and also title AND having alertview for each button??pls suggest me answer..
//array taken for button titles
NSArray *array1=[NSArray arrayWithObjects:#"1",#"2",#"3",#"4",#"5", nil];
int k=0;
for(int i=50;i<=350;i=i+70)
{
button=[UIButton buttonWithType:UIButtonTypeRoundedRect];
button.frame=CGRectMake(30,i,35,40);
[button addTarget:self action:#selector(buttonclicked:) forControlEvents:UIControlEventTouchUpInside];
if (k<[array1 count])
{
[button setTitle:[array1 objectAtIndex:k] forState:UIControlStateNormal];
}
k++;
[self.view addSubview:button];
}
Try this
-(void) buttonClicked:(id) sender
{
UIButton * button = (UIButton*) sender;
button.backgroundColor = [UIColor yellowcolor];
[button setTitle:#"Hello" forState:UIControlStateNormal];
}
Set the tag for each button and when it's call buttonclicked: is called, then use it's tag rod decide which background color to set it to::
int temptag;
temptag = 0;
for(int i=50;i<=350;i=i+70)
{
button=[UIButton buttonWithType:UIButtonTypeRoundedRect];
button.frame=CGRectMake(30,i,35,40);
[button addTarget:self action:#selector(buttonclicked:) forControlEvents:UIControlEventTouchUpInside];
button.tag = temptag;
if (k<[array1 count])
{
  [button setTitle:[array1 objectAtIndex:k] forState:UIControlStateNormal];
  }
k++;  
temptag++;
[self.view addSubview:button];
}
-(void)buttonclicked:(id)sender
{
UIButton *btn = (UIButton *)sender;
switch (btn.tag) {
case 0:
btn.backgroundColor = [UIColor redColor];
break;
case 1:
btn.backgroundColor = [UIColor grayColor];
break;
case ...:
....
default:
break;
}
}

Scroll to center of UIScrollview clicked UIButton added programmatically EDITED

I have a scrollview of scrollview of UIbuttons build like this:
-(void) loadCompeticionSlide{
float x=0;
for (int i = 0; i < [categoriasArray count]; i++) {
NSDictionary *categoria = [categoriasArray objectAtIndex:i];
UIButton *btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
NSString *titleString = [categoria valueForKey:#"competicion"]; // get button title
btn.titleLabel.font = [UIFont boldSystemFontOfSize:11.0];
CGSize fontSize = [titleString sizeWithFont:[UIFont systemFontOfSize:11.0]];
CGRect currentFrame = btn.frame;
CGRect buttonFrame = CGRectMake(x, currentFrame.origin.y, fontSize.width + 22.0, fontSize.height + 12.0);
[btn setFrame:buttonFrame];
x = x + fontSize.width + 35.0;
[btn setTitle:titleString forState: UIControlStateNormal];
int idc = [[categoria valueForKey:#"idc"]intValue];
[btn addTarget:self action:#selector(cambiarCompeticion:) forControlEvents:UIControlEventTouchUpInside];
[btn setTag:idc];
[self.competicionSlide addSubview:btn];
}
//[competicionSlide setBackgroundColor:[UIColor whiteColor]];
competicionSlide.contentSize = CGSizeMake(350,35);
competicionSlide.layer.cornerRadius = 11;
competicionSlide.layer.masksToBounds = YES;
}
Then, in the added selector cambiarCompeticion:, I got the button clicked, here I need to use scrollRectToVisible: to get the clicked UIButton scrolled to the center of the UIScrollview that contains it, but I don't know how to do it.
This is the selector method triggered by button selection where I understand scrollRectToVisible: has to be called:
-(void)cambiarCompeticion:(UIButton*)boton{
int idCompeticion;
idCompeticion = boton.tag;
switch (idCompeticion) {
case 1:
[self tablaLigaRegular];
break;
case 5:
[self tablaCoparey];
break;
case 10:
[self tablaPlayOff];
break;
}
}
here are the details in images, in first image blue arrow indicates previous state of the partial hidden left button and the move to do to the middle of scroll view once it is clicked:
many thanks
Your boton parameter (from the cambiarCompeticion: selector) has everything you need. Just call like this (assuming that "competicionSlide" is an UIScrollView) :
[self.competicionSlide scrollRectToVisible:boton.frame];
Good luck !