UIButton : managing dynamic creation and touch events - iphone

I'm currently dynamically creating UIButton objects in my view.
I have an NSMutableArray containing information about them (id - label).
I then create my view objects by doing a for iteration on my MutableArray.
I'm trying to use this code on my buttons to catch touche events :
[myButton addTarget:self action:#selector(selectedButton:) forControlEvents:UIControlEventTouchUpInside];
My selectedButton method is called with success, but I don't have any idea on knowing with button were touched.
I tried to do this :
-(void)selectedButton:(id)sender {...}
But don't know what to do with the sender object.
Thanks in advance for your help !

At the top of your .m file, put something like this:
enum {
kButtonOne,
kButtonTwo
};
When you're creating your buttons, do this
myButton.tag = kButtonOne;
Then in your selected button method, do this:
-(void)selectedButton:(id)sender {
switch (sender.tag) {
case kButtonOne:
// do something here
break;
case kButtonTwo:
// do something else here
break;
}
}

Set mybutton.tag to something, and then check for that tag in selectedButton:sender.

-(void)viewDidLoad{
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
button.frame = CGRectMake(80.0, 210.0, 40.0, 30.0);
button.tag=1;
[button addTarget:self
action:#selector(aMethod:)
forControlEvents:UIControlEventTouchDown];
[button setTitle:#"raaz" forState:UIControlStateNormal];
[self.view addSubview:button];
}
-(IBAction)aMethod:(id)sender{
UIButton *btn=(UIButton *)sender;
NSLog(#"I have currently Pressed button=%d",btn.tag);
}

Related

Respond to touches on programmatically generated custom UIButtons inside UIScrollView

I have a UIScrollView full of custom UIButtons that are generated programmatically.
This code executes every iteration through the loop, typically 7 times.
[cardButton
addTarget:self
action:#selector(buttonPressed:)
forControlEvents:UIControlEventTouchUpInside];
[cardButton setTag:i + 100];
[self.scrollView addSubview:cardButton];
Elsewhere I have this function:
- (IBAction) buttonPressed:(id)sender
{
UIButton *button = (UIButton *)sender;
NSLog(#"%d", [button tag]);
}
How do I link the two? My button actually stores all the information I need from it inside its label so I really just need to detect when it is being tapped so I can respond.
You already linked two with this line
[cardButton
addTarget:self
action:#selector(buttonPressed:)
forControlEvents:UIControlEventTouchUpInside];
Sender is returning the instance of button which you pressed.so
- (IBAction) buttonPressed:(id)sender
{
UIButton *button = (UIButton *)sender;
NSLog(#"%d", [button tag]);
switch (button.tag) {
case 1:
//Action for button with tag 1
break;
case 2:
//Action for button with tag 2
break;
default:
break;
}
}

How to identify which button is clicked in Objective-C?

I am a new iPad developer.
I have created UIButton programmatically, in which I want to identify user has clicked on which button and according to that I want to do some action.
How should I identify this?
Here is my code snippet:
for(int i=0;i<[_array count];i++)
{
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
button.tag=count;
[button addTarget:self
action:#selector(aMethod:)
forControlEvents:UIControlEventTouchDown];
button.backgroundColor=[UIColor redColor];
[button setTitle:#"Show View" forState:UIControlStateNormal];
button.frame = CGRectMake(xpos, 270.0, 200.0, 150.0);
[self.view addSubview:button];
}
This is what I'm doing now: I thought I will assign count to each button and I will pass this count to button click method. Is this a good idea? Is there any other way possible?
On button click I'm calling aMethod:
-(void)aMethod:(id)sender{
NSLog(#"btn clicked");
}
Any help will be appreciated!
-(void)aMethod:(UIButton*)sender{
NSLog(#"btn clicked %d", sender.tag);
}

how to create various UIButtons with a for case in iPhone SDK?

I have something like this...
for(int i=0;i<10;i++){
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[button addTarget:self action:#selector(myMethod:) forControlEvents:UIControlEventTouchDown];
[button setTitle:#"Button1" forState:UIControlStateNormal];
button.frame = CGRectMake(00.0, 00.0, 100.0, 30.0);
[view addSubview:button];
}
It's possible to instantiate each button with his own id? For example button+i ?
Thanks in advance!
You can set a numeric id to each button using the tag property:
button.tag = i;
You can then get the button instance afterwards with the code
[view viewWithTag:i];
provided you have added it to a view, like using [view addSubview:button].

Add a multiple buttons to a view programmatically, call the same method, determine which button it was

I want to programmatically add multiple UIButtons to a view - the number of buttons is unknown at compile time.
I can make one or more UIButton's like so (in a loop, but shorted for simplicity):
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[button addTarget:self
action:#selector(buttonClicked:)
forControlEvents:UIControlEventTouchDown];
[button setTitle:#"Button x" forState:UIControlStateNormal];
button.frame = CGRectMake(100.0, 100.0, 120.0, 50.0);
[view addSubview:button];
Copied/Edited from this link:
How do I create a basic UIButton programmatically?
But how do I determine in buttonClicked: which button was clicked? I'd like to pass tag data if possible to identify the button.
You could either keep a reference to the actual button object somewhere that mattered (like an array) or set the button's tag to something useful (like an offset in some other data array). For example (using the tag, since this is generally must useful):
for( int i = 0; i < 5; i++ ) {
UIButton* aButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[aButton setTag:i];
[aButton addTarget:self action:#selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
[aView addSubview:aButton];
}
// then ...
- (void)buttonClicked:(UIButton*)button
{
NSLog(#"Button %ld clicked.", (long int)[button tag]);
}
You can assign a tag to the button.
button.tag = i;
Then in -buttonClicked:, check the tag of the sender:
-(void)buttonClicked:(UIButton*)sender {
int tag = sender.tag;
...
}
I think this would be the best answer:-
http://conecode.com/news/2012/05/ios-how-to-create-a-grid-of-uibuttons/
For that give different tag to each button & use code like this:
[btn1 addTarget:self action:#selector(pressbtn:) forControlEvents:UIControlEventTouchUpInside];
[btn2 addTarget:self action:#selector(pressbtn:) forControlEvents:UIControlEventTouchUpInside];
& in method
-(void)pressbtn:(id)sender {
UIButton *button=sender;
if (button.tag==1)
{
NSLog(#"Press button 1");
}
if (button.tag==2)
{
NSLog(#"Press button 2");
}
and so on to check which button is called
If you want to add buttons at run time then there will be 10 20 50 or more than that. Then you should to use ui scroll view in this condition.
When the buttons will be generate then your scroll view size should be increased accordingly.
And you can write the code like this
scrollview = [[UIScrollView alloc] init];
scrollview.contentSize = CGSizeMake(INVOICE_ADDITEM_SCROLLVIEW_CONTENT_WIDTH, INVOICE_ADDITEM_SCROLLVIEW_CONTENT_HEIGHT);
scrollview.frame = CGRectMake(0,50, SCROLLVIEW_WIDTH, SCROLLVIEW_HEIGHT);
// scrollview.backgroundColor = [UIColor whiteColor];
scrollview.scrollsToTop = NO;
scrollview.delegate = self;
[self.view addSubview:scrollview];
for (int pos = 0; pos < 2; pos++) {
UIButton *but = [UIButton buttonWithType:UIButtonTypeCustom];
[but setImage:[UIImage imageNamed:#"checkbox.png"] forState:UIControlStateNormal];
[but setImage:[UIImage imageNamed:#"checkbox_active.png"] forState:UIControlStateSelected];
[but setFrame:CGRectMake(TXT_FLD_X_CORD+90, 295, 20, 20)];
// [but setCenter:CGPointMake( 50, i*40+20 )];
but.tag = pos;
/*if(pos==0)
{
[but setImage:[UIImage imageNamed:#"checkbox_active.png"] forState:UIControlStateNormal];
// [but setImage:[UIImage imageNamed:#"checkbox_active.png"] forState:UIControlStateSelected];
}*/
[but setCenter:CGPointMake(pos*90+125 ,310)];
[but addTarget:self action:#selector(checkboxButton:) forControlEvents:UIControlEventTouchUpInside];
[scrollview addSubview:but];
}
UIButton has a tag property. Use that and in your buttonClicked method, you can check the button that was clicked based on it's tag. Might want to keep constants around for what button is what.
For each of your buttons set an appropriate tag, and then refer to the tag in your action. i.e.
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
...
button.tag = 1
[view addSubview:button];
You can easily set the tag based on the index of your iteration, if you're creating buttons in a loop. And then in your action:
- (void)aButtonWasTapped:(UIButton *)source {
if( source.tag == 1 ) {
// etc
}
}
Somebody might have this problem:
Jason Coco's answer worked fine for me, until I wanted to use the tag to access properties from an NSArray that was defined as a property.
Turns out the property had to be defined as "retain" instead of "weak".
The Swift version (with Labels):
for index in 1...5 {
var label = UILabel()
label.tag = index
labelsDictionary["Label\(index)"] = label
self.addSubview(label)
}
Call using using self.viewWithTag(i) as UILabel:
(cell.viewWithTag(5) as UILabel).text

What is the best way to make a UIButton checkbox?

I am trying to make a standard check box for my iPhone app from a UIButton with a title and image. The button image changes between an "unchecked" image and a "checked" image.
At first I tried subclassing UIButton but UIButton has no -init*** method to use in my -init method.
What is the best way to do this?
Thanks in advance.
You shouldn't need to subclass the UIButton class. By design, Objective-C favors composition over inheritance.
UIButton is a subclass of UIControl, which has a selected property. You can use this property to toggle the on/off behaviour of a checkbox, just the same way a UISwitch does.
You can attach an action to the button's touched up inside event, and perform the toggling in there, something like this:
// when you setup your button, set an image for the selected and normal states
[myCheckBoxButton setImage:checkedImage forState:UIControlStateSelected];
[myCheckBoxButton setImage:nonCheckedImage forState:UIControlStateNormal];
- (void)myCheckboxToggle:(id)sender
{
myCheckboxButton.selected = !myCheckboxButton.selected; // toggle the selected property, just a simple BOOL
}
Set the images in the button:
[button setImage:uncheckedImage forState:UIControlStateNormal]
[button setImage:checkedImage forState:UIControlStateSelected]
Now all you need to do is:
button.selected = state
and the correct images will display.
All you need to do is set 2 different images for the states UIControlStateNormal and UIControlStateSelected, then in your selector, changed the selected property of the button.
Here is a working example (replace image names with your own):
- (void)loadView {
// ...
UIButton *chkBtn = [UIButton buttonWithType:UIButtonTypeCustom];
[chkBtn setFrame:CGRectMake(0, 0, 300, 25)];
[chkBtn setImage:[UIImage imageNamed:#"UNCHECKED.png"]
forState:UIControlStateNormal];
[chkBtn setImage:[UIImage imageNamed:#"CHECKED.png"]
forState:UIControlStateSelected];
[chkBtn addTarget:self
action:#selector(chkBtnHandler:)
forControlEvents:UIControlEventTouchUpInside];
// Optional title change for checked/unchecked
[chkBtn setTitle:#"I am NOT checked!"
forState:UIControlStateNormal];
[chkBtn setTitle:#"I am checked!"
forState:UIControlStateSelected];
[self.view addSubview:chkBtn];
[chkBtn release], chkBtn = nil;
// ...
}
- (void)chkBtnHandler:(UIButton *)sender {
// If checked, uncheck and visa versa
[sender setSelected:!sender isSelected];
}
For anyone interested in the future - instead of doing it yourself just download the link below from GitHub and it has it subclassed from UIControl already and functions perfectly as a checkbox. Also includes a sample project on how easy it is to use:
https://github.com/Brayden/UICheckbox
I have used M13Checkbox in one of my projects. Works ok.
https://github.com/Marxon13/M13Checkbox
Did you try overriding the initWithCoder method, just in case it is loaded from a nib somehow?
UIImage* nonCheckedImage=[UIImage imageNamed:#"ic_check_box_outline_blank_grey600_48dp.png"];//[UIImage init
UIImage* CheckedImage=[UIImage imageNamed:#"ic_check_box_black_48dp.png"];//[UIImage init
//ic_check_box_black_48dp.png
[_checkBox setImage:CheckedImage forState:UIControlStateSelected];
[_checkBox setImage:nonCheckedImage forState:UIControlStateNormal];
}
- (IBAction)checkBoxToggle:(id)sender {
_checkBox.selected = !_checkBox.selected; // toggle the selected property, just a simple BOOL
}
the image you can use google icon
Try this:-
-(IBAction)clickCheckButton:(UIButton *)sender {
if (sender.tag==0) {
sender.tag = 1;
[sender setImage:[UIImage imageNamed:#"check.png"] forState:UIControlStateNormal];
}else
{
sender.tag = 0;
[sender setImage:[UIImage imageNamed:#"uncheck.png"] forState:UIControlStateNormal]; } } sender.tag = 0;
[sender setImage:[UIImage imageNamed:#"uncheck.png"] forState:UIControlStateNormal];
}
}
Why not use a switch - UISwitch? This is used to display an element showing the boolean state of a value.