我正在创建一个包含动态页面的应用程序。实际上,我通过检查服务器的响应创建了一些动态问题和UIButtons(自定义复选框)。 我的代码在这里,
NSString *response=[ResponseFromServer ObjectAtIndex:0];
if ([comSt compare: @"CheckBoxList"]==NSOrderedSame)
{
int count=[ResponseFromServer count];
for(int i=0;i<count;i++)
{
button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
button.tag=i;
[button setFrame:CGRectMake(0.0f, 0.0f, 37, 37)];
[button setCenter:CGPointMake(116.0,p1)];
[button setImage:[UIImage imageNamed:@"uncheck.png"] forState:UIControlStateNormal];
[button setBackgroundColor:[UIColor whiteColor]];
[button addTarget:self action:@selector(checkButtonTapped:) forControlEvents:UIControlEventTouchUpInside];
[self.scrollView addSubview:button];
p1=p1+30;
}
-(void)checkButtonTapped:(id)sender
{
int tagVal = [(UIButton*)sender tag];
if (tagVal==0) {
NSLog(@"tag = 0");
[button setSelected:YES];
[button setImage:[UIImage imageNamed:@"check.png" forState:UIControlStateSelected]; //not working, button image is not changing
}
假设我创建了5个带有不同标签的动态按钮。我首先将所有这些按钮的图像设置为uncheck.png。有用。 但当我点击一个特定按钮并需要将该按钮图像更改为checked.png时,它不会对按钮操作起作用。 我需要像checkBox控件一样更改它,我将如何从一组按钮访问动态创建按钮的控件?
我想你可以理解我的要求,提前谢谢......
答案 0 :(得分:0)
在您的代码中,您需要像这样更改
试试此代码
if ([comSt compare: @"CheckBoxList"]==NSOrderedSame)
{
int count=[ResponseFromServer count];
for(int i=0;i<count;i++)
{
button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
button.tag=0;
[button setFrame:CGRectMake(0.0f, 0.0f, 37, 37)];
[button setCenter:CGPointMake(116.0,p1)];
[button setImage:[UIImage imageNamed:@"uncheck.png"] forState:UIControlStateNormal];
[button setBackgroundColor:[UIColor whiteColor]];
[button addTarget:self action:@selector(checkButtonTapped:) forControlEvents:UIControlEventTouchUpInside];
[self.scrollView addSubview:button];
p1=p1+30;
}
}
-(void)checkButtonTapped:(id)sender
{
int tagVal = [(UIButton*)sender tag];
if (tagVal==0) {
NSLog(@"tag = 0");
[button setSelected:YES];
[button setImage:[UIImage imageNamed:@"check.png" forState:UIControlStateSelected];
[button setTag:100];
}
else
{
[button setSelected:YES];
[button setImage:[UIImage imageNamed:@"uncheck.png" forState:UIControlStateSelected];
[button setTag:0];
}
}
答案 1 :(得分:0)
添加动态按钮组[按钮setSelected:NO];
替换方法并添加下面给出的一种方法
-(void)checkButtonTapped:(id)sender
{
UIButton *curButton = (UIButton*)sender
if (curButton.tag==0)
{
[self buttonAction:curButton];
}
if (curButton.tag==1)
{
[self buttonAction:curButton];
}
// continues
}
-(void)buttonAction:(UIButton *)curButton
{
if(![curButton isSelected])
{
[curButton setSelected:YES];
[curButton setImage:[UIImage imageNamed:@"check.png" forState:UIControlStateSelected]; //not working, button image is not changing
} else {
[curButton setSelected:NO];
[curButton setImage:[UIImage imageNamed:@"uncheck.png"] forState:UIControlStateNormal];
}
}