我试图在UITableView中输出我的NSMutableArray,tableView正在显示,但它的输出是不正确的数据。我期待这样的事情
Check 10
Try 11
Test 12
这是我的代码
- (void)viewDidLoad
{
arr1 = [[NSMutableArray alloc] initWithObjects:@"Check",@"Try",@"Test" ,nil];
arr2 = [[NSMutableArray alloc] initWithObjects:@"10",@"11",@"12", nil];
self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 400, 500, 500)];
self.tableView.dataSource = self;
self.delegate = self;
[self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"cells"];
[self.view addSubview:self.tableView];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cells" forIndexPath:indexPath];
UIImageView *images = [[UIImageView alloc] initWithFrame:CGRectMake(8, 8, 50, 50)];
[images setImage:[UIImage imageNamed:[img objectAtIndex:indexPath.row]]];
[cell addSubview:images];
UILabel *label1 = [[UILabel alloc] initWithFrame:CGRectMake(131, 27, 59, 21)];
label1.text = [arr1 objectAtIndex:indexPath.row];
[cell addSubview:label1];
UILabel *label2 = [[UILabel alloc] initWithFrame:CGRectMake(231, 27, 67, 21)];
label2.text = [arr2 objectAtIndex:indexPath.row];
[cell addSubview:label2];
return cell;
}
它的输出是
Check 10
Try 11
Check 10
答案 0 :(得分:3)
请不要在tableview委托的cellForRowAtIndex中添加SubView。因为它被多次调用。在您的情况下,自定义UITableViewCell,例如:
MyTableViewCell.h:
@interface MyTableViewCell : UITableViewCell
- (void)setImages:(UIImage *)images label1:(NSString *)label1 label2:(NSString *)label2;
@end
MyTableViewCell.m:
@interface MyTableViewCell()
@property (nonatomic, strong) UIImageView *images;
@property (nonatomic, strong) UILabel *label1;
@property (nonatomic, strong) UILabel *label2;
@end
@implementation MyTableViewCell
- (void)awakeFromNib {
[super awakeFromNib];
_images = [[UIImageView alloc] initWithFrame:CGRectMake(8, 8, 50, 50)];
[self addSubview:_images];
_label1 = [[UILabel alloc] initWithFrame:CGRectMake(131, 27, 59, 21)];
[self addSubview:_label1];
_label2 = [[UILabel alloc] initWithFrame:CGRectMake(231, 27, 67, 21)];
[self addSubview:_label2];
}
- (void)setImages:(UIImage *)images label1:(NSString *)label1 label2:(NSString *)label2 {
_images.image = images;
_label1.text = label1;
_label2.text = label2;
}
修改你的代码:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
MyTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cells" forIndexPath:indexPath];
UIImage *image = [UIImage imageNamed:[img objectAtIndex:indexPath.row]];
NSString *text1 = [arr1 objectAtIndex:indexPath.row];
NSString *text2 = [arr2 objectAtIndex:indexPath.row];
[cell setImages:image label1:text1label2:text2];
return cell;
}