我想动态创建uibuttons。所以我循环创建带标签的按钮并添加到视图中。 所有按钮对其标签值执行相同的操作...但我想更改按钮的属性。因此我需要使用标签值来获取uibutton ...
我的代码......
UIButton *button2;
//view did load
int width = 30;
for(int i = 1; i <= 5; i++)
{
button2 = [UIButton buttonWithType:UIButtonTypeCustom];
[button2 addTarget:self action:@selector(ratingAction:) forControlEvents:UIControlEventTouchUpInside];
[button2 setBackgroundImage:[UIImage imageNamed:@"star1.png"] forState:UIControlStateNormal];
button2.tag = i;
button2.backgroundColor = [UIColor clearColor];
button2.frame = CGRectMake(width, 78, 15, 15);
[self.view addSubview:button2];
width = width +30;
}
-(void)ratingAction:(id*)sender
{
// here using the tag value i want to get the button and change the background image….
// for example i want to change the background for tag values 1,3,6,7 ,8…
}
答案 0 :(得分:1)
答案 1 :(得分:1)
-(void)ratingAction:(id*)sender
{
// here using the tag value i want to get the button and change the background image….
// for example i want to change the background for tag values 1,3,6,7 ,8…
if ([sender isKindOfClass:[UIButton class]])
{
UIButton *temp=(UIButton*)sender;
if ([temp tag]==1 || [temp tag]==3 || [temp tag]==6 || [temp tag]==7 )
{
[temp setBackgroundColor:[UIColor redColor]];
}
}
}
答案 2 :(得分:0)
检查此代码
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
int y = 100;
for (int i=0; i<=5; i++) {
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[button addTarget:self
action:@selector(aMethod:)
forControlEvents:UIControlEventTouchDown];
[button setTitle:@"Show View" forState:UIControlStateNormal];
button.frame = CGRectMake(80, y, 160, 40);
[button setTitle:[NSString stringWithFormat:@"Button-%i", i] forState:UIControlStateNormal];
// [button set
[self.view addSubview:button];
y=y+60;
}
}
-(void)aMethod:(id)sender{
UIButton *button = sender;
int y = 100;
int i = 5;
for (int x=0; x<=i; x++) {
NSString *frameString = [NSString stringWithFormat:@"{{80, %i}, {160, 40}}", y];
if ([NSStringFromCGRect(button.frame) isEqualToString:frameString]) {
NSLog(@"button %i clicked..", x);
}
y= y+60;
}
}