我正在尝试创建自定义调查问卷。我有多个NSMutableArray(btnAr),我存储按钮组。为了保持秩序,我使用另一个NSMutableArray(radioGroupBtns),其中存储了所有NSMutableArrays(btnAr)。
我使用tableview来显示按钮。我面临的问题是:
当我点击第一组中的按钮时,滚动到最后一组后,也会点击相同的按钮。
正确的图像是我在底部滚动的时候。
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return 5;
}
-(UITableViewCell* )tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
FeedbackViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kCellIdentifier];
NSInteger rowNum = [indexPath row];
NSLog(@"RowNumb: %ld",rowNum);
NSMutableArray *btns = [radioGroupBtns objectAtIndex:rowNum];
NSMutableArray *lbls = [radioGroupLabels objectAtIndex:rowNum];
for (int i=0; i<[btns count]; i++)
{
[cell addSubview:[btns objectAtIndex:i]];
[cell addSubview:[lbls objectAtIndex:i]];
}
return cell;
}
-(void) getData
{
int totalSections = 5;
for (int j=0; j<totalSections; j++)
{
NSMutableArray *btnAr = [[NSMutableArray alloc]init];
NSMutableArray *lblAr = [[NSMutableArray alloc]init];
int numOfQuestions = 4;
for (int i=0; i<numOfQuestions; i++)
{
RadioUIButton *button = [self getButton:i];
button.sectionTag = j;
button.stringTag = [NSString stringWithFormat:@"%d%d", i,button.sectionTag];
[button setTag:i];
UILabel *lbl = [self getLabel:i text:@"Question"];
[lblAr addObject:lbl];
[btnAr addObject:button];
}
[radioGroupBtns addObject:btnAr];
[radioGroupLabels addObject:lblAr];
}
}
- (void) btnPressed:(id) b
{
RadioUIButton *btn = (RadioUIButton *) b;
NSMutableArray *group = [radioGroupBtns objectAtIndex:btn.sectionTag];
for (RadioUIButton *bn in group)
{
if ([bn tag] != [b tag])
{
if ([bn isSelected])
[bn setSelected:!bn.selected];
}
}
if (![btn isSelected])
[btn setSelected:!btn.selected];
NSLog(@"Button %ld clicked. Row: %d , String: %@", (long int)[b tag], btn.sectionTag, btn.stringTag);
}
- (RadioUIButton*) getButton:(int) i {
RadioUIButton *button = [RadioUIButton buttonWithType:UIButtonTypeCustom];
int hpos = i*30 + 30;
button.frame = CGRectMake(30.0f, hpos, 30.0f, 30.0f);
[button addTarget:self action:@selector(btnPressed:) forControlEvents:UIControlEventTouchUpInside];
//[button setTitle:@"Option A" forState:UIControlStateNormal];
[button setImage: [UIImage imageNamed:@"radio_button_off.png"]forState:UIControlStateNormal];
[button setImage: [UIImage imageNamed:@"radio_button_on.png"]forState: UIControlStateSelected];
return button;
}
- (UILabel*) getLabel:(int) i text:(NSString *) txt{
int hpos = i*30 + 30;
UILabel *label = [[UILabel alloc] init];
label.frame = CGRectMake(80,hpos,200,30);
label.text = txt;
return label;
}
答案 0 :(得分:1)
表视图重用单元格。有办法解决这个问题。但是,在您的情况下,您似乎不需要重复使用单元格。因此,请使用滚动视图,并在其中充气视图。 作为建议,尝试存储模型对象而不是按钮。根据数据模型处理视图及其状态。