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 = (arc4开发者_Python百科random() % 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:
.
精彩评论