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.
Related
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);
}
}
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]];
}
}
}
What I am trying to do is align views in a grid that are in an array. I have created the views and the array.
for (int i = 0; i < [directoryContents count]; i++){
UIView *containerView = [[UIView alloc] initWithFrame:CGRectMake(0,0,100,120)];
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[button addTarget:self action:#selector(buttonPressed:) forControlEvents:UIControlEventTouchDown];
[button setTitle:#"Show View" forState:UIControlStateNormal];
button.frame = CGRectMake(0, 0, 100, 100);
button.accessibilityIdentifier = [directoryContents objectAtIndex:i];
UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(0, 100, 100, 20)];
label.textAlignment = NSTextAlignmentCenter;
label.text = [directoryContents objectAtIndex:i];
[containerView addSubview:button];
[containerView addSubview:label];
[self.view addSubview:containerView];
[_containerViewArray addObject:containerView];
}
[self layoutViews:_containerViewArray inView:self.view];
What I have working is aligning them next to each other the problem I am having is I need to have them wrap down instead of going off the edge. What I am doing to algin them is this
- (void)layoutViews:(NSArray *)views inView:(UIView *)contentView
{
NSInteger overallWidth = 0;
for ( UIView *view in views ) {
overallWidth += view.frame.size.width;
}
CGSize contentSize = contentView.frame.size;
CGFloat startOffset = (contentSize.height - overallWidth)/2.0;
CGFloat offset = startOffset;
for ( UIView *view in views ) {
CGRect frame = view.frame;
frame.origin.x = offset;
view.frame = frame;
offset += view.frame.size.width;
}
}
If we assumed that we have an array of sections (your views) and you need to layout 3 item per row the view has size 98*98 and spacing 6.5px horizontally and 8px Vertically
for (int i = 0; i< [sectionsArray count]; i++) {
int row = (int)i/3;
int col = i%3;
float x = 6.5 + (104.5*col);
float y = 8 + (106*row);
UIView *sectionView = [[UIView alloc] initWithFrame:CGRectMake(x, y, 98, 98)];
sectionView.backgroundColor = [UIColor clearColor];
//button
UIButton *sectionButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[sectionButton setTintColor:[UIColor grayColor]];
sectionButton.frame = CGRectMake(0, 0, 98, 98);
sectionButton.tag = i+100;
[sectionButton addTarget:self action:#selector(showSectionDetail:) forControlEvents:UIControlEventTouchUpInside];
[sectionView addSubview:sectionButton];
//adding title
UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 75, 98, 20)];
titleLabel.textAlignment = UITextAlignmentCenter;
titleLabel.backgroundColor=[UIColor clearColor];
titleLabel.font=[UIFont fontWithName:#"Helvetica" size:14];
titleLabel.textColor = [UIColor colorWithRed:241.0/255.0 green:124.0/255.0 blue:22.0/255.0 alpha:1.0];
titleLabel.text = [[sectionsArray objectAtIndex:i] objectForKey:#"Title"];
[sectionView addSubview:titleLabel];
[titleLabel release];
[scroll addSubview:sectionView];
[sectionView release];
}
int numberOfRows;
if ([sectionsArray count]/3.0f == 0) {
numberOfRows = [sectionsArray count]/3;
}else{
numberOfRows = [sectionsArray count]/3 +1;
}
scroll setContentSize:CGSizeMake(320, numberOfRows*106);
Here's what I used until the UICollectionView was released, easy to modify to accommodate for how many rows you want in the grid, and the size of the views.
NSUInteger buttonWidth = 100;
NSUInteger buttonHeight = 100;
NSUInteger space = 5;
float scrollContentY = (ceilf((float)imageNames.count / 3.0f) * (buttonHeight + space));
[myArray enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
int row = idx / 3;
int column = idx % 3;
UIView *view = [UIView new];
[view setBackgroundColor:[UIColor redColor]];
view.frame = CGRectMake((buttonWidth + space) * column + space, (buttonHeight + space) * row + space , buttonWidth, buttonHeight);
[view setTag:(NSInteger)idx];
[self.scrollView addSubview:view];
[self.scrollView setContentSize:CGSizeMake(self.scrollView.frame.size.width, scrollContentY)];
}];
Mind you, this might not be advisable if you have a large array to enumerate because this doesn't have any kind of reusable views. It will alloc/init a view for every item in the array.
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;
}
}
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 !