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

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;
}
}

Related

Button's Tag are same in TableView

I add view for header, here is my code:
-(UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
UIView *view = [[UIView alloc] init];
view.layer.borderWidth = 0.5;
view.layer.borderColor = [UIColor colorWithRed:127.0/255.0 green:229.0/255.0 blue:232.0/255.0 alpha:1.0].CGColor;
view.backgroundColor = [UIColor clearColor];
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(30, 0, 150, 50)];
label.text = sectionArray[section];
label.backgroundColor = [UIColor clearColor];
label.textColor = [UIColor colorWithRed:0.0 green:122.0/255.0 blue:1.0 alpha:1.0];
button = [[UIButton alloc] initWithFrame:CGRectMake(self.myTableView.frame.size.width - 50, 15, 20, 20)];
[button setImage:[UIImage imageNamed:#"down"] forState:UIControlStateNormal];
button.tag = section;
[button addTarget:self action:#selector(extentFunction) forControlEvents:UIControlEventTouchUpInside];
[view addSubview:label];
[view addSubview:button];
return view;
}
-(void)extentFunction {
switch (button.tag) {
case 0:
NSLog(#"0");
break;
case 1:
NSLog(#"1");
break;
case 2:
NSLog(#"2");
break;
case 3:
NSLog(#"3");
break;
default:
break;
}
}
The question is: the button's tag is same of each header, not the section integer (ex: first header button's tag is 0; second header button's tag is 1)that I want.
What should I do?
As first look its clear issue of local & global variable.
You need to define your button as local variable and use button action sender as button object and get tag from that button.
Look at below code I think it will help you to understand your issue:
-(UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
UIView *view = [[UIView alloc] init];
view.layer.borderWidth = 0.5;
view.layer.borderColor = [UIColor colorWithRed:127.0/255.0 green:229.0/255.0 blue:232.0/255.0 alpha:1.0].CGColor;
view.backgroundColor = [UIColor clearColor];
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(30, 0, 150, 50)];
label.text = sectionArray[section];
label.backgroundColor = [UIColor clearColor];
label.textColor = [UIColor colorWithRed:0.0 green:122.0/255.0 blue:1.0 alpha:1.0];
//Make Your Button local object not global
UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(self.myTableView.frame.size.width - 50, 15, 20, 20)];
[button setImage:[UIImage imageNamed:#"down"] forState:UIControlStateNormal];
button.tag = section;
[button addTarget:self action:#selector(extentFunction) forControlEvents:UIControlEventTouchUpInside];
[view addSubview:label];
[view addSubview:button];
return view;
}
-(IBAction)btnClick:(UIButton*)sender{
switch (sender.tag) {
case 0:
NSLog(#"0");
break;
case 1:
NSLog(#"1");
break;
case 2:
NSLog(#"2");
break;
case 3:
NSLog(#"3");
break;
default:
break;
}
}
Let me know if its working fine.
This is your custom button code which is correct.
UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(self.myTableView.frame.size.width - 50, 15, 20, 20)];
[button setImage:[UIImage imageNamed:#"down"] forState:UIControlStateNormal];
button.tag = section;
[button addTarget:self action:#selector(extentFunction) forControlEvents:UIControlEventTouchUpInside];
But you also need to add its sender and event to get the touch location of your button like below code.
[button addTarget:self action:#selector(extentFunction:event:) forControlEvents:UIControlEventTouchUpInside];
Now when you will click on button, extentFunction selector will get called. Now all you have to do is implement your button selector like below code.
-(void)extentFunction:(id)sender event:(id)event{
NSSet *touches = [event allTouches];
UITouch *touch = [touches anyObject];
CGPoint currentTouchPosition = [touch locationInView:_yourTableViewName];
NSIndexPath *indexPath = [_yourTableViewName indexPathForRowAtPoint: currentTouchPosition];
NSLog(#"%ld",indexPath.section);
}
Hope this will help you out.

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

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]];
}
}
}

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 have a UIButton image change when a button is touched

I'm trying to have the UIButton image change when a button is touched. Currently I it changes but only on the highlighted state change. I would like it to change and stay there. I tried UIControlStateSelected for the state change but no luck.
thanks for the help
here's my code:
// Create buttons for the sliding category menu.
NSMutableArray* buttonArray = [NSMutableArray array];
NSArray * myImages = [NSArray arrayWithObjects:#"category-cafe-unsel.png", #"category-food-unsel.png", #"category-clothing-unsel.png", #"category-health-unsel.png", #"category-tech-unsel_phone.png" , #"category-tech2-unsel.png", #"catefory-theatre-unsel.png", #"category-travel-unsel.png", nil];
NSArray * myImagesSel = [NSArray arrayWithObjects:#"category-cafe-sel.png", #"category-food-sel.png", #"category-clothing-sel.png", #"category-health-sel.png", #"category-tech-sel_phone.png" , #"category-tech2-sel.png", #"catefory-theatre-sel.png", #"category-travel-sel.png", nil];
// only create the amount of buttons based on the image array count
for(int i = 0;i < [myImages count]; i++)
{
// Custom UIButton
btn = [UIButton buttonWithType:UIButtonTypeCustom];
[btn setFrame:CGRectMake(0.0f, 20.0f, 52.0f, 52.0f)];
[btn setTitle:[NSString stringWithFormat:#"Button %d", i] forState:UIControlStateNormal];
[btn setImage:[UIImage imageNamed:[myImages objectAtIndex:i]] forState:UIControlStateNormal];
[btn setImage:[UIImage imageNamed:[myImagesSel objectAtIndex:i]] forState:UIControlStateHighlighted];
NSLog(#"The button title is %# ", btn.titleLabel.text);
[btn addTarget:self action:#selector(buttonPressed:) forControlEvents:UIControlEventTouchUpInside];
[buttonArray addObject:btn];
In your IBAction method add the following lines:
- (IBAction)change:(id)sender
{
UIButton *button = (UIButton *)sender;
int tagOfButton = button.tag - 1;
[button setImage:[UIImage imageNamed:[myImagesSel objectAtIndex:tagOfButton]] forState:UIControlStateNormal];
}
Add a single line to your for loop like:
for(int i = 0;i < [myImages count]; i++)
{
// other stuffs
btn.tag = i+1;
}
EDIT:
If you need to undone the previous selection when other button is clicked:
write this loop inside your IBAction method.
for(int i = 0;i < [myImages count]; i++)
{
UIButton *but = (UIButton *)[buttonArray objectAtIndex:i];
if(but != button)
{
[btn setImage:[UIImage imageNamed:[myImages objectAtIndex:i]] forState:UIControlStateNormal];
}
}
Or simply store the previous button tag to a variable.
And use it to change undone the image change.
[btn setTitle:#"I'm not selected" forState:UIControlStateNormal];
[btn setImage:[UIImage imageNamed:[myImages objectAtIndex:i]] forState:UIControlStateNormal];
[btn setTitle:#"I'm selected" forState:UIControlStateSelected];
[btn setImage:[UIImage imageNamed:[myImagesSel objectAtIndex:i]] forState:UIControlStateSelected];
[btn addTarget:self action:#selector(buttonPressed:) forControlEvents:UIControlEventTouchUpInside];
-(IBAction)buttonPressed:(id)sender {
btn.selected = !btn.selected;
}

Trouble with "viewWithTag"

oldTag button is not changing back to white ??
What am I missing?
thx
-(void) myCharValue: (UIButton*)btn
{
[btn setBackgroundColor:[UIColor redColor]]; //current tag_button pressed
UIButton *btnTemp;
btnTemp = (UIButton*)[btnChar viewWithTag:oldTag];
[btnTemp setBackgroundColor:[UIColor whiteColor]]; // <--- oldTag button is not changing back to white ??
oldTag = btn.tag;
}
//setup
for (int i=0; i<16; i++) {
for (int j=0; j<16; j++) {
btnChar = [UIButton buttonWithType:UIButtonTypeCustom ];
[btnChar setFrame:CGRectMake(j*40+1, i*40+1, 38, 38)];
[btnChar setBackgroundColor:[UIColor whiteColor]];
[btnChar setTitle:[NSString stringWithFormat:#"%c", k] forState:UIControlStateNormal ];
[btnChar setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[btnChar addTarget:self action:#selector(myCharValue:) forControlEvents:UIControlEventTouchUpInside];
[btnChar setTag:k];
[svDisplay addSubview:btnChar];
k++;
}
}
I just want to add that the default value of tag property is 0, so if you start your loop with 0, first button will technically not be tagged. Later when you request a viewWithTag: 0 from svDisplay (chech #jrtc27's answer), you will get a first view in that [svDisplay subviews] array.
Your buttons are subviews of svDisplay, not btnChar, so the line btnTemp = (UIButton*)[btnChar viewWithTag:oldTag]; should be btnTemp = (UIButton*)[svDisplay viewWithTag:oldTag];.