好吧,我创建了一个单选按钮在每个单元格中的简单表格视图,这是为了了解为什么单元格重复。我把我的行数设置得很高,表明单元格确实重复了。这个简单的项目的目标是在解决这个问题时得出一个合理的结论,因为在这个主题上有几篇文章没有给出正确的结果。当用户在单元格中选择一个按钮时,只有该单元格应该受到影响。这是整个代码。UItableViewCells重复
#import "faQViewController.h"
@interface faQViewController()
@end
@implementation faQViewController
@synthesize button1,button2;
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone) {
return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
} else {
return YES;
}
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return 30;
}
-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
static NSString *cellIdentifier [email protected]"cell";
button1 = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[button1 addTarget:self action:@selector(buttonPressed:) forControlEvents:UIControlEventTouchUpInside];
button1.frame = CGRectMake(0, 0, 22, 32);
[button1 setImage:[UIImage imageNamed:@"radioOff.png"] forState:UIControlStateNormal];
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if (cell ==nil) {
cell = [[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier
] autorelease];
cell.selectionStyle = UITableViewCellSelectionStyleGray;
[cell.contentView
addSubview:button1];
}
// cell.imageView.image = [UIImage imageNamed:@"radioOff.png"];
return cell;
}
-(IBAction)buttonPressed:(id)sender{
if ([sender imageForState:UIControlStateNormal ]== [UIImage imageNamed:@"radioOff.png"]){
[sender setImage:[UIImage imageNamed:@"radioOn"] forState:UIControlStateNormal];
}else {
[sender setImage:[UIImage imageNamed:@"radioOff.png"] forState:UIControlStateNormal];
}
}
什么不行? – Mundi 2012-07-26 17:50:46
究竟是什么问题?单元格不会在tableViews中重复使用,您正在重用单元格。 – ohr 2012-07-26 17:57:19
你觉得'dequeueReusableCellWithIdentifier:'中的'Reusable'这个词是什么意思? – 2012-07-26 18:03:55