【发布时间】:2016-02-11 06:01:17
【问题描述】:
我以编程方式创建了UIButtons 并将它们添加到我的UIScrollView。现在我想将点击的UIButton 的背景图像更改为图像,其他图像应保持为默认颜色的蓝色。现在当我点击另一个UIButton,我想将之前点击的UIButton 更改为蓝色,当前点击的按钮有背景图片。
这是创建和设置UIButton属性的代码:
for (int i=0; i<[arrPartVenuDetails count]; i++) {
NSString *venueId = [[arrPartVenuDetails objectAtIndex:i] objectForKey:@"venue_id"];
NSInteger venue_id= [venueId integerValue];
NSLog(@"venue id %ld",(long)venue_id);
aButton = [UIButton buttonWithType:UIButtonTypeCustom];
[aButton setFrame:CGRectMake(10.0f, 10.0f, 100.0f, 20.f)];
[aButton setBackgroundColor:[UIColor colorWithRed:(6/255.0) green:(130/255.0) blue:(195/255.0) alpha:1]];
NSString *buttonClassName = [NSString stringWithFormat:@"VENUE %d", i+1];
[aButton.titleLabel setTextAlignment: NSTextAlignmentCenter];
[aButton setTitle:buttonClassName forState:UIControlStateNormal];
aButton.frame = CGRectMake(xCoord, yCoord,buttonWidth,buttonHeight );
[aButton addTarget:self action:@selector(venueButtonClick:) forControlEvents:UIControlEventTouchUpInside];
aButton.tag = venue_id;
[scrollVenue addSubview:aButton];
yCoord += buttonHeight + buffer;
}
这是按钮点击方法:
-(void) venueButtonClick:(UIButton *)sender{
[sender setBackgroundImage:[UIImage imageNamed:@"venue .png"] forState:UIControlStateNormal];
CGRect btnOnclickFrame = sender.frame;
btnOnclickFrame.size.width = 210;
sender.frame = btnOnclickFrame;
}
【问题讨论】:
-
在按钮的点击事件中,检查它的标签。如果是第一个按钮,则将其背景颜色设置为红色,将所有其他按钮设置为默认蓝色。像这样,您可以对所有其他按钮执行此操作。
-
您已经在为按钮设置标签。如果您不使用它们,它们有什么用? (虽然事实上我很难学到标签一点都不好)
标签: ios objective-c iphone uibutton