Change a specific button in a grid - objective-c

I'm using this to define a grid of buttons. I want to programmatically change the attribute of a specific button, like:
if(button.tag == 6)
{
[button setBackgroundImage:imageRed forState:UIControlStateNormal];
[button setImage:imageRed forState:UIControlStateNormal];
}
Button creation below.
for (int y=0; y < 3; y++) {
for (int x = 0; x < 3; x++) {
UIButton * button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
//button.frame = CGRectMake(40 + 80 * x, 40 + 80 * y, 80, 80);
button.frame=CGRectMake(5+5*x,5+5*y,5,5);
unsigned buttonNumber = y * 3 + x + 1;
button.tag = buttonNumber;
//[button setTitle:[NSString stringWithFormat:#"%u", buttonNumber] forState:UIControlStateNormal];
[button setBackgroundImage:imageWhite forState:UIControlStateNormal];
[button setImage:imageWhite forState:UIControlStateNormal];
[button addTarget:self action:#selector(buttonPressed:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview: button];
}
}

I'm not entirely sure what your question is, but it seems like 'how do I find a view with a specific tag?'. The answer is the UIView method
- (UIView *)viewWithTag:(NSInteger)tag
This will look through the current view and all it's subviews for the specified tag and return the first view it finds that matches it. So to get, for example, the button with tag 6, just do:
UIView* button = [self.view viewWithTag:6];
Of course, when dealing with a target method, like your buttonPressed: method, the view that triggered the event is passed as a parameter, so you can also use that if that's the only time you need it. Other than that everything in your code looks fine.

I ended up using this...
for (int row = 0; row < ROWS; row++) {
for (int col = 0; col < COLS; col++) {
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
// [ButtonArray addObject:button];
button.tag = row * COLS + col;
button.frame = CGRectMake(5+5*row,5+5*col,5,5);
[button addTarget:self action:#selector(didPushButton:) forControlEvents:UIControlEventTouchDown];
[button setBackgroundImage:imageWhite forState:UIControlStateNormal];
[button setImage:imageWhite forState:UIControlStateNormal];
[self.view addSubview:button];
buttonArr[row*COLS+col]=button;
}
}

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

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

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

how to draw Square button in iOS under navigation bar

I have this code and I want to have my button as a square, and also under the navigation bar,would you plase help me
Thanks in advance!
I want to have my button as a square
- (void)viewDidLoad
{
[super viewDidLoad];
int rows = 13, columns = 4;
UIView *buttonView = [[UIView alloc] initWithFrame:CGRectMake(0.f, 0.f, 70*columns, 70*rows)];
for (int y = 0; y < rows; y++) {
for (int x = 0; x < columns; x++) {
UIButton * button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
button.frame = CGRectMake(70 * x, 28 * y, 70, 28);
[button addTarget:self action:#selector(buttonPressed:) forControlEvents:UIControlEventTouchUpInside];
[buttonView addSubview: button];
}
}
// Center the view which contains your buttons
CGPoint centerPoint = buttonView.center;
centerPoint.x = self.view.center.x;
buttonView.center = centerPoint;
[self.view addSubview:buttonView];
}
-(void)buttonPressed:(UIButton *)button
{
NSLog(#"button %u -- frame: %#", button.tag, NSStringFromCGRect(button.frame));
}
Edit 2
my error when I using border
[button.layer setBorderWidth:1.0];
[button.layer setBorderColor:[UIColor blackColor]];
Define an integer variable and set this as button title
int rows = 13, columns = 4;
int number=1;
UIView *buttonView = [[UIView alloc] initWithFrame:CGRectMake(0.f,44, 70*columns, 70*rows)];
for (int y = 0; y < rows; y++) {
for (int x = 0; x < columns; x++) {
UIButton * button = [UIButton buttonWithType:UIButtonTypeCustom];
button.frame = CGRectMake(75 * x, 75 * y, 70, 70);
button.backgroundColor=[UIColor redColor];
[button setTitle:[NSString stringWithFormat:#"%d",number] forState:UIControlStateNormal];
button.tag=number;
[button addTarget:self action:#selector(buttonPressed:) forControlEvents:UIControlEventTouchUpInside];
[buttonView addSubview: button];
number++;
}
}
Hope this will help you to move to next screen. Button.tag gives the exact button you have selected.
You are setting your button of size 70x28, so if you want a button 70x70, you have to change button.frame = CGRectMake(70*x, 70*y, 70, 70), this way you will have square buttons.
Also, are you sure this is a NavigationBar or just a Toolbar? If you use NavigationController which uses navigationBar, Apple's own SDK will not allow you to easily draw over it.
In any case in your case, just start drawing your buttons from y = 44 down and you won't have buttons overlap the toolbar.
Try this
int rows = 13, columns = 4;
UIView *buttonView = [[UIView alloc] initWithFrame:CGRectMake(0.f,44, 70*columns, 70*rows)];
for (int y = 0; y < rows; y++) {
for (int x = 0; x < columns; x++) {
UIButton * button = [UIButton buttonWithType:UIButtonTypeCustom];
button.frame = CGRectMake(75 * x, 75 * y, 70, 70);
button.backgroundColor=[UIColor redColor];
[button addTarget:self action:#selector(buttonPressed:) forControlEvents:UIControlEventTouchUpInside];
[buttonView addSubview: button];
}
}
// Center the view which contains your buttons
CGPoint centerPoint = buttonView.center;
centerPoint.x = self.view.center.x;
buttonView.center = centerPoint;
[self.view addSubview:buttonView];
For using layer property you need to add QuartzCore.framework in your project.

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 !