Adding arguments to selector in addTarget - iphone

I'm having trouble adding arguments to the selector of a button (programmatically created). I've looked around the internet and tried some things, but I can't figure it out.
I create a button with the following line:
NSString *someThing = [[NSString alloc] initWithString:#"someThing"];
int counter = 4;
[anotherButton addTarget:self action:#selector(alertPressed:) forControlEvents:UIControlEventTouchUpInside];
I've got the function alertPressed:
-(void)alertPressed:(id)sender {
}
How can I transfer those two variables to alertPressed?

You can subclass UIButton, with a custom button that contains those attributes. Then, your (id)sender can be cast to your custom button and you can obtain the set values.

Why not global variables or properties in your class?

Related

How To point to an object from string

My question is kind of general; in my project I have 10 UIButton objects
named Button1, Button2, Button3, Button4, Button5, Button6, Button7, Button8, Button9, and Button10
I also have UIImageview That are named exactly like the buttons from 1 to 10.
I want to write a code that will manipulate the image by the last character of the button (always a number from 1 to 10) and will affect the UIImageview the same way
Something like this
buttonlastcharacter = i;
if(sender.lastcharacternumber is:i){
Button%,i.frame = //Some manipulation
But basically all that I want is to have access to a certain object by string
How can I implement such a behavior?
There are a couple of better ways to do this. If these buttons are all static and in IB you can use an IBCollection array for image views and buttons to simply call them up by matching indexes.
Better yet just use the tag value for the buttons or image views.
It is maybe not the ideal solution in your case, but you can do it different ways:
using kvo
UIButton* myButton = [self valueForKey:[NSString stringWithFormat:#"button%i",i]];
or with selectors and properties
UIButton* myButton = [self performSelector:NSSelectorFromString([NSString stringWithFormat:#"button%i",i])];
Hm, you could use an array for your buttons and a tag for your UIImageView objects. They all inherit from UIView, which provides you with a .tag propterty. It is of type NSInteger* .
For convenience reasons I would suggest to name the buttons from 0 to 9. It does not really matter but the first index in the array would be 0 and therefore naming them accordingly just makes things easier.
Define
NSArray *buttonArray;
You may opt for NSMutableArray depending what else you may want to do with it.
In viewDidLoad code:
buttonArray = [NSArray arrayWithCapacity:10];
buttonArray[0] = button0;
..
buttonArray[9] = button9;
In your XIB file in Interface Builder, or whereever you may create the UIImages programmatically, add the tags accordingly.
image0.tag = 0;
...
image0.tag = 9;
assuming you name them image0 to image9.
In your appropriate action method code:
buttonArray[sender.tag] = someManipulation;
You can do it like this,
In your IBAction method:
- (IBAction)click:(id)sender
{
UIButton *but = (UIButton *)sender;
but.frame = your manipulation code;
}
or you can check the title like:
if([but.currentTitle isEqualToString:#"Button1])
{
//Manipulate button 1
}
if you have added tags for the buttons from 1-10 you can use,
if(but.tag == 2)
{
//Manipulate button 2
}

Return customized UIButton in method?

I have a method that takes a UIButton, modifies its properties and returns a UIButton. However, it doesn't ever seem to be initialized. I'm sure I'm doing something wrong with the memory management here, but don't exactly know how to fix it. No runtime errors occur.
It is called like so...
newGameBtn = [self customButtonFromButton:newGameBtn
withText:[NSString stringWithFormat:#"NEW GAME"]
withFontSize:22
withBorderColor:[UIColor orangeColor]
isSilent:YES];
[dashboardContainer addSubview:newGameBtn];
The method is defined as follows...
- (UIButton*) customButtonFromButton:(UIButton*)button withText:(NSString*)text withFontSize:(int)fontSize withBorderColor:(UIColor*)borderColor isSilent:(BOOL)isSilent {
button = [[[UIButton alloc] init] autorelease];
// Set properties from parameters
// Other conditional custom stuff here
return button;
}
NOTE: newGameBtn is of type UIButton* and is initialized with:
newGameBtn = [[UIButton buttonWithType:UIButtonTypeCustom] retain];
Another option might be to subclass UIButton, but I figured I'd try to fix this since I've already walked down this path.
You should use +[UIButton buttonWithType:] when creating buttons to get a properly initialized button.
Most classes are not properly initialized by the default -[NSObject init] method. So please look at the class reference, or superclass reference, for a usable initialization method.
In this case you should also set a frame.
You don't modify this button with your method, you're creating a completely new one with alloc-init!
If you want to change the button in your first argument just remove the first line of your method

Cast NSString to UIButton type

Im trying to cast a string to a button type. Basically, Im looping through, say 5 buttons, named btn1,btn2..btn5. Here's the snippet:
- (IBAction)replaceImg
{
UIButton* b;
for(int i=0; i<5; i++)
{
b = (UIButton*)[NSString stringWithFormat:#"btn%d",i]; //1!
if([b isHighlighted])
{
int imgNo = (arc4random() % 6) + 1;
UIImage *img = [UIImage imageNamed:[NSStringstringWithFormat:#"%d.png", imgNo]];
[b setImage:img forState:(UIControlState)UIControlStateNormal];
}
}
}
The line marked 1 is giving a problem, if I swap it with b = btn1, it works perfectly. Please help!
I couldnt find a way to access a button by its name either. Like UIImage has something like imageNamed.
you can't cast NSString to UIButton because both are completely different type.
Use tag property of UIView to assign and unique number to each UIButton and at any point of time you could access them by using viewWithTag .
You can't 'cast' an NSString to a button. To get specific buttons, or buttons by name, depends on how you created them. Store your created buttons into an array, or if they come from a NIB then gather their pointers into an array, then loop through the array of button pointers. Controls are also UIViews, so you can assign a numeric 'tag' to each button in Interface Builder then use UIView's viewWithTag: method to search for a specific view with a specific tag.
An NSString isn't a UIButton, so casting it to one isn't going to work. Well, it might work as far as syntax goes, but logic-wise, it will fail. You simply cannot interact with an NSString the same way you can a UIButton. If you need to find your button by name, then you can either retain pointers to those buttons (either in an array, a map, or just as plain instance variables, to name a few ways), or you could alternatively use something like viewWithTag:.

Using a random integer to call an object

If I have a random integer e.g. randomInt and want to call a created button e.g. UIButton *button1, button2, button3 etc.
Will I be able to call the button as follows
NSString *buttonNumber = [NSString stringWithFormat:#"button%d", randomInt];
[buttonNumber setImage:[UIImage imageNamed:#"someImage.png"] forState:UIControlStateNormal];
I have a lot of these and it would decrease code amount dramatically.
Thanks
Create then Store your buttons in an NS(Mutable)Array then access them using:
UIButton* button = [buttonArray objectAtIndex:randomInt];
When you create the button assign a tag to the button like
button.tag = number
you can get the button later with
[[parentview viewWithTag:randomInt] setimage:...]
If the UIButtons are properties of your self object, you can do it like this:
[[self valueForKey:buttonNumber] setImage:...]
Its better to use the tags with the button. It will help you a lot and it will reduce the code than you currently are using.
-hAPPY iCODING...

2D Array of UIButtons Isn't Working (Objective-C/iPhone development)

I've made a bunch of UIButtons in a grid and I want to be able to iterate over them easily so I've put them in an NSMutableArray.
Like so:
// in .h
UIButton* button1;
UIButton* button2;
...
UIButton* button9;
UIButton* myButtons[3][3];
// in init function in app
myButtons[0][0] = button1;
myButtons[0][1] = button2;
...
myButtons[2][2] = button9;
But now if I try to access the title of a button in myButtons I get nil:
// elsewhere in app
[button1 setTitle:#"A" forState:UIControlStateNormal];
// and then:
NSLog(#"currentTitle of button1: %#", (myButtons[0][0]).currentTitle); // -> (null)
Anybody know what's going on? Thanks!
first of all, that's not an NSMutableArray, it's just a plain ol' array.
Second, where do you set button1 to a non-null value? Is it before or after assigning myButtons[0][0] = button1;? I would check and make sure that myButtons[0][0] is non-null when calling the NSLog method. If it is, then you need to assign your array later or assign the buttons earlier.