Creating UIButton programmatically with custom class - ios

I want to create 3-4 buttons programmatically but with a custom class and a specific value/key pair, but I struggle on how to do this exactly.
The button I want to create must have a custom class named "AnswerButton". Adding a UIButton.tag shouldnt be a problem, so I can exactly tell what button has been clicked, right?
Here is the code I use to create buttons:
NSMutableArray *catNames;
catNames = [NSMutableArray arrayWithCapacity:5];
[catNames addObject:#"Boote"];
[catNames addObject:#"Gewässer"];
[catNames addObject:#"Technik"];
[catNames addObject:#"Krims Krams"];
[self dynamiclyCreateButtons:4 :catNames];
- (void)dynamiclyCreateButtons:(int)howMany :(NSMutableArray*)catNames {
float standard_btnHeight = 30.0;
float standard_btnWidth = 200.0;
CGFloat p = 120;
for(int i = 0; i != howMany; i++){
UIButton *catBtn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[catBtn setFrame:CGRectMake(0.0f, 0.0f, standard_btnWidth, standard_btnHeight)];
[catBtn setCenter:CGPointMake(100.0f, p)];
[catBtn setTitle:[catNames objectAtIndex:i] forState:UIControlStateNormal];
[catBtn addTarget:self action:#selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:catBtn];
p=p+40;
catBtn = nil;
}
}
//Edit
What I mean by custom class:
https://i.stack.imgur.com/8r2oz.png
//Edit 2 (The correct answer, since I cannot post an answer myself to point it out better)
Just here to point it out and find the answer easier: Answer by Greg is correct.
You shouldn't create the buttons with the default class but with your custom class instead:
Replace
UIButton *catBtn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
with
AnswerButton *catBtn = [AnswerButton buttonWithType:UIButtonTypeRoundedRect];
Dont forget to import the class!

Try This...
-(void)dynamiclyCreateButtons:(int)howMany :(NSMutableArray*)catNames {
float standard_btnHeight = 30.0;
float standard_btnWidth = 200.0;
CGFloat p = 120;
for(int i = 0; i != howMany; i++){
UIButton *catBtn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[catBtn setFrame:CGRectMake(0.0f, 0.0f, standard_btnWidth, standard_btnHeight)];
[catBtn setCenter:CGPointMake(100.0f, p)];
[catBtn setTag:i];
[catBtn setTitle:[catNames objectAtIndex:i] forState:UIControlStateNormal];
[catBtn addTarget:self action:#selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:catBtn];
p=p+40;
catBtn = nil;
}
}
- (IBAction)buttonClicked:(id)sender
{
NSLog(#"Button.Tag = %d",[sender tag]);
}
EDIT: If you want to use the custom class, you have to create a class inherited from UIButton. Then import this class in your view controller.
After that replace UIButton with YourCustomButton like..
YourCustomButton *catBtn = [YourCustomButton buttonWithType:UIButtonTypeRoundedRect];

Related

getting element from array one by one and createbutton

I have a UItextFeild as search bar on clicking a tableview with suggestion open.now i want to click on that row and make a button with its label in below view as described in image .how can i acheive this
I want it one by one means when i click on row it create a button on view and UITableView hide then again i start searching and on again clicking on some other row make a button with different value of X.
_selectednames = [NSMutableArray arrayWithCapacity:self.sortedArray.count];
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
// MGContactItemsModel *model = _arrayForContacts[indexPath.row];
self.searchText.text = [NSString stringWithFormat:#"%#",[_sortedArray objectAtIndex:indexPath.row]];
self.tableView.hidden = YES;
[_selectednames addObject:_searchText.text];
for (int i; i < _selectednames.count ; i++) {
[self makeLabelsAndButtons:i];
}
now in my makeLabelsAndButtons funtion i done something like this
CGFloat xOffset = 10.0f;
int buttonCount = 0;
CGRect buttonFrame = CGRectMake(xOffset, 10.0, 50.0, 15.0);
NSString *nameString = [self.selectednames objectAtIndex:indexPath];
UIButton *_button = [UIButton buttonWithType:UIButtonTypeCustom];
[_button addTarget:self action:#selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
//_button.frame = CGRectMake(xOffset, 10.0, 50.0, 15.0);
for(int i=buttonCount; i >0;i++) {
xOffset = xOffset+10;
buttonFrame.origin.x += buttonFrame.size.width+xOffset;
}
_button.frame = buttonFrame;
buttonCount++;
_button.tag = indexPath;
//button.center = CGPointMake(xOffset, 10.0f);
//[button setBackgroundImage:[UIImage imageNamed:picString] forState: UIControlStateNormal];
[_button setTitle:self.selectednames[indexPath] forState:UIControlStateNormal];
_button.backgroundColor = [UIColor lightGrayColor];
_button.titleLabel.font = [UIFont fontWithName:#"Arial" size:8.0f];
_button.layer.cornerRadius = 10.0f;
_button.layer.masksToBounds = YES;
[self.buttonView addSubview:_button];
NSLog(#"name: %#", nameString);
also on clicking button it will removed.any help would be thankful.
It works for me.Please try it.
y=20;
x=20;
for (int i=0; i<[arrAssignUsers count]; i++) {
CGRect screenRect=[[UIScreen mainScreen]bounds];
CGFloat screenWidth=screenRect.size.width;
[arrBtnStatus addObject:[NSNumber numberWithBool:NO]];
NSString *strNames=[arrAssignUsers objectAtIndex:i];
stringsize=[strNames sizeWithAttributes:
#{NSFontAttributeName: [UIFont systemFontOfSize:20.0f]}];
btn=[UIButton buttonWithType:UIButtonTypeRoundedRect];
CGFloat m=x+stringsize.width+10;
CGFloat n=screenWidth-20;
if (m<=n) {
btn.frame=CGRectMake(x, y,stringsize.width,stringsize.height);
x=x+stringsize.width +10;
}
else
{
y=y+stringsize.height+10;
x=20;
btn.frame=CGRectMake(x, y,stringsize.width,stringsize.height);
x=x+stringsize.width+10;
}
[btn setTitle:self.arrAssignUsers[i] forState:UIControlStateNormal];
[btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
btn.tag=i;
[btn addTarget:self
action:#selector(notifyButtonPressedInEditTask:) forControlEvents:UIControlEventTouchUpInside];
btn.backgroundColor=WHITE_COLOR;
btn.layer.cornerRadius=10;
[btn.layer setMasksToBounds:YES];
btn.layer.borderWidth=2.0f;
btn.layer.borderColor=[UIColor orangeColor].CGColor;
[self checkNotifybtnStatus:btn];
[cell addSubview:btn];
}
}
It may helps to you.Thank you
You can use UICollectionView to create buttons. All you need to do is
1. Create custom cell with button as you want
2. When you tap on table view cell, add item to array and reload UICollectionView
3. Show buttons and it will automatically add scrollview for you.
When you tap on UICollectionView cell, remove object from array and reload UICollectionView again.
This will more easy as compared to adding buttons and setting frames.
And design UICollectionView cell in such way that it will same length as your text, use NSLayoutConstraints for it. It will work fast and smooth.
Code will be minimum and reusable.
Try out this working code...
Take UIScrollView in your Xib for buttons
//Adding menu buttons
btnArray = #[#"SYMPTOMATIC", #"SOCIAL", #"VOCATIONAL", #"PERSONAL"];
[self addButtonsInScrollMenu:btnArray];
/**
* Add Menu Buttons in Menu Scroll View
*
* #param buttonArray Array containing all menu button title
*/
#pragma mark - Add Menu Buttons in Menu Scroll View
-(void) addButtonsInScrollMenu:(NSArray *)buttonArray
{
CGFloat buttonHeight = self.menuScrollView.frame.size.height;
CGFloat cWidth = 0.0f;
for (int i = 0 ; i<buttonArray.count; i++)
{
NSString *tagTitle = [buttonArray objectAtIndex:i];
CGFloat buttonWidth = [self widthForMenuTitle:tagTitle buttonEdgeInsets:kDefaultEdgeInsets];
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
button.frame = CGRectMake(cWidth, 0.0f, buttonWidth, buttonHeight);
[button setTitle:tagTitle forState:UIControlStateNormal];
button.titleLabel.font = [UIFont fontWithName:#"Roboto-Regular" size:12.0f];
[button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
//[button setTitleColor:[UIColor lightGrayColor] forState:UIControlStateSelected];
[button addTarget:self action:#selector(buttonPressed:) forControlEvents:UIControlEventTouchUpInside];
button.tag = i;
[self.menuScrollView addSubview:button];
UIView *bottomView = [[UIView alloc] initWithFrame:CGRectMake(0, button.frame.size.height - kButtonBorderHeight, button.frame.size.width, kButtonBorderHeight)];
bottomView.backgroundColor = [UIColor darkTextColor];
bottomView.tag = 1001;
[button addSubview:bottomView];
if (i == 0)
{
button.selected = YES;
[bottomView setHidden:NO];
}
else
{
[bottomView setHidden:YES];
}
cWidth += buttonWidth;
}
NSLog(#"scroll menu width->%f",cWidth);
self.menuScrollView.contentSize = CGSizeMake(cWidth, self.menuScrollView.frame.size.height);
}

get tag of UIButton and those with smaller tags

I'm not understanding if what I'm trying to do is possible or not.
I am creating buttons in for loop:
CGRect rect2 = CGRectMake(50, 230, 40, 40);
for (int i = 0; i<5; i++) {
NSString *stringI = [NSString stringWithFormat:#"%d",i+1];
NSString *stringItouch = [NSString stringWithFormat:#"%dselected",i+1];
UIButton *button = [[UIButton alloc] init];
[button setBackgroundImage:[UIImage imageNamed:stringI] forState:UIControlStateNormal];
[button setBackgroundImage:[UIImage imageNamed:stringItouch] forState:UIControlStateSelected];
[button addTarget:self action:#selector(touchButton:) forControlEvents:UIControlEventTouchUpInside];
button.tag = i+1;
button.frame = rect2;
rect2.origin.x = rect2.origin.x + 45;
[scrollView addSubview:button];
}
and after in method touchButton i get the tag of touched button
-(void)touchButton:(id)sender {
UIButton *buttonSender = sender;
buttonSender.selected = YES;
NSLog(#"button tag %#",buttonSender.tag);
for (int i = buttonSender.tag-1; i>0; i--) {
NSLog(#"int = %d",i);
//for example if buttonSender.tag is 4, in this way i have 3,2,1
}
}
in the last loop i want to select the buttons that have the tag less than that touched (in this case 3,2,1)
is it possible or not???
thanks everybody
All you need is viewWithTag: like so:
-(void)touchButton:(id)sender {
UIButton *buttonSender = sender;
buttonSender.selected = YES;
NSLog(#"button tag %#",buttonSender.tag);
for (int i = buttonSender.tag-1; i>0; i--) {
NSLog(#"int = %d",i);
//for example if buttonSender.tag is 4, in this way i have 3,2,1
/* Add this line */
UIButton *tempButton = (UIButton *)[scrollView viewWithTag:i];
}
}

How to get index of uiimage subview of uiscrollview

I need to detect selected image of uiimage which is placed inside scrollview.
My code is here:
int newscrollviewY = 40;
for(int i = 0; i<1; i++)
{
scrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(5, newscrollviewY, 310, 100)];
scrollView.showsVerticalScrollIndicator = YES;
scrollView.scrollEnabled = YES;
scrollView.userInteractionEnabled = YES;
scrollView.backgroundColor = [UIColor clearColor];
scrollView.delegate=self;
int imgx = 1;
for(int img=0; img<[images count]; img++)
{
UIImageView *imageView1 = [[UIImageView alloc]initWithFrame:CGRectMake(imgx,0,100,100)];
imageView1.backgroundColor = [UIColor whiteColor];
imageView1.image = [images objectAtIndex:img];
imageView1.contentMode = UIViewContentModeScaleAspectFit;
[imageView1 setNeedsDisplay];
[imageView1 setUserInteractionEnabled:YES];
[imageView1 setMultipleTouchEnabled:YES];
[scrollView addSubview:imageView1];
imageButton = [UIButton buttonWithType:UIButtonTypeCustom];
imageButton.frame = CGRectMake(imgx,0,100,100);
[imageButton addTarget:self action:#selector(buttonClicked) forControlEvents:UIControlEventTouchUpInside];
imageButton.tag = img;
[scrollView addSubview:imageButton];
imgx = imgx + 103;
}
Please help to detect selected image using imageButton or something else.
Replace your selector with buttonClicked:
be Sure that you are adding ":" after selector method. follow or replace the code below:
[imageButton addTarget:self action:#selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
then Add the selector definantion in .m file
- (void) buttonClicked: (id) sender
{
// here you can get the tag of button.
NSInteger tag = ((UIButton *)sender).tag;
// do your implementation after this
}
Hope this will solve your issue. Enjoy Coding..!!
They way you have set it up the tag of the 'button' is already the number of the image in your array of images. So all you need to do is get the tag from the 'button'.
Make sure the button clicked function retrieves the tag from the sender(id) that you receive.
For example a bit like this:
- (IBAction)buttonClicked:(id)sender {
UIButton *button = (UIButton *)sender;
UIImage selectedImages = [images objectForKey: [button tag]];
}
As par you question if you are using UIImageview you have to use UITapGestureRecognizer that same like Button. you just need to add UITapGestureRecognizer like:-
for(int img=0; img<[images count]; img++)
{
UIImageView *imageView1 = [[UIImageView alloc]initWithFrame:CGRectMake(imgx,0,100,100)];
imageView1.backgroundColor = [UIColor whiteColor];
UITapGestureRecognizer *frameTapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(frameTapGesture:)];
frameTapGesture.numberOfTapsRequired=1;
imageView1.image = [images objectAtIndex:img];
imageView1.contentMode = UIViewContentModeScaleAspectFit;
[imageView1 setNeedsDisplay];
[imageView1 setUserInteractionEnabled:YES];
[imageView1 setMultipleTouchEnabled:YES];
imageView1.tag=img;
[_imgView addGestureRecognizer:frameTapGesture];
[scrollView addSubview:imageView1];
}.
- (void)frameTapGesture:(UITapGestureRecognizer*)sender
{
UIView *view = sender.view; //cast pointer to the derived class if needed
NSLog(#"%d", view.tag);
}
Reduce your code There are No need to add Button with same Frame of ImageView For getting Click Event or you can also set Image of UIButton for you want to like use UIBUtton then remove UIImageview Code else you simply use UITapGestureRecognizer with getting click event using - (void)frameTapGesture:(UITapGestureRecognizer*)sender
Please try this code
for(int img=0; img<[images count]; img++)
{
imageButton = [UIButton buttonWithType:UIButtonTypeCustom];
[imageButton setImage:[UIImage imageNamed:[images objectAtIndex:i]] forState:UIControlStateNormal];
imageButton.frame = CGRectMake(imgx,0,100,100);
[imageButton addTarget:self action:#selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
imageButton.tag = img;
[scrollView addSubview:imageButton];
imgx = imgx + 103;
}
- (void) buttonClicked: (id) sender
{
UIButton *button = (UIButton *)sender;
UIImage selectedImage = button.currentImage;
}
set button target
[button addTarget:self action:#selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
// get Button Action
-(void) buttonAction:(UIButton *)sender
{
NSLog(#"%dl",sender.tag);
// do your implementation after this
}

text not visible after moving UIButtons

float newY = 0;
CGRect buttonFrame;
for(int i=1; i<=countTabItems;i++){
id item = [self viewWithTag:i];
if([item isKindOfClass:[UIButton class]]){
UIButton *button = item;
[item release];
NSLog(#"got %#", button.titleLabel.text);
buttonFrame = button.frame;
buttonFrame.size.height = self.frame.size.height/countTabItems;
buttonFrame.size.width = self.frame.size.width;
buttonFrame.origin.x = 0;
buttonFrame.origin.y = newY;
button.frame = buttonFrame;
[button setTitle:#"TEST" forState:UIControlStateNormal];
NSLog(#"%0.2f",newY);
[button release];
newY += frame.size.height/countTabItems;
}
}
Can someone tell me what is problem with this code, please. I use this to move buttons from their original position after which the UIButton is not showing any Title (text) on it.
[self viewWithTag:i]; does not retain anything so the release of item object should not be there. The same goes for the release of the button object. Try to remove those two releases and see if it solves your problem.

Adding actions to a button programmatically on iOS

I am trying to add an action to buttons which I am creating programmatically:
[btn addTarget:self
action:#selector(indexAction)
forControlEvents:UIControlEventTouchUpInside];
This works fine. However, I now want to pass a variable (int k) to the indexAction method. I couldn't get this to work:
[btn addTarget:self
action:#selector([self indexAction:k])
forControlEvents:UIControlEventTouchUpInside];
I am sure I'm doing something wrong. This is the context of the above code:
-(void) initIndexButtons {
float buttonPadding = -8;
float buttonWidth = 23;
float buttonHeight = 80;
CGRect frame = CGRectMake(0,0,0,0);
for (int k=0;k<5;k++)
{
UIButton* btn = [[UIButton alloc] initWithFrame:frame];; btn.tag = k;
btn.frame = CGRectMake(0, k*(buttonPadding+buttonHeight), buttonWidth, buttonHeight);
UIImage *newImage = [UIImage imageNamed:#"index.png"];
[btn setBackgroundImage:newImage forState:UIControlStateNormal];
[btn addTarget:self
action:#selector(self indexAction:k)
forControlEvents:UIControlEventTouchUpInside];
}
}
-(void)indexAction:(int *)buttonTag
{
NSLog(#"buttonTag: %i", buttonTag);
}
EDIT:
I changed my code to:
// ...
[btn addTarget:self
action:#selector(indexAction:)
forControlEvents:UIControlEventTouchUpInside];
//[self indexAction:k];
[indexView addSubview:btn];
[indexView sendSubviewToBack:btn];
}
}
-(void)indexAction:(id)sender
{
NSInteger *tid = ((UIControl *) sender).tag;
NSLog(#"buttonTag: %i", tid);
}
But now I get the warning message that "Initialisation makes pointer from integer without a cast for the line NSInteger *tid = ((UIControl *) sender).tag;
EDIT:
This is the right line of code:
NSInteger tid = ((UIControl*)sender).tag;
Normally the method that a button calls takes one parameter:
(id)sender
Take a look at the question - how to pass a variable to a UIButton action
tag is an NSInteger not NSInteger*
change to
NSInteger tid = ((UIControl*)sender).tag;
The way to do it is to set:
-(void)indexAction:(id)sender
{
NSLog(#"Tag=%#"[(UIButton*)sender tag]);
}
and the call:
[btn addTarget:self
action:#selector(self indexAction:)
forControlEvents:UIControlEventTouchUpInside];
}
not really sure about my casting, haven't tested that, but I think it should work!
Best of luck.

Resources