我有一个奇怪的问题,我正在设置一个非常基本的 TableView 来显示联系人,我有如下所示的 tabelviewcontroller(我试图包括所有相关部分),但由于某种原因,当我运行应用程序时我有每个表格单元格(全部七个)中出现相同的数据标签。有人可以看到我看不到的错误吗...非常感谢
以下所有代码均来自tableviewcontroller.m 我让我的数组在 View 中加载
- (void)viewDidLoad
{
[super viewDidLoad];
// Uncomment the following line to preserve selection between presentations.
// self.clearsSelectionOnViewWillAppear = NO;
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem;
self.contacts = [NSMutableArray arrayWithCapacity:10];
Contact *contact = [[Contact alloc] init];
contact.name = @"1";
[self.contacts addObject:contact];
contact.name = @"2";
[self.contacts addObject:contact];
contact.name = @"3";
[self.contacts addObject:contact];
contact.name = @"4";
[self.contacts addObject:contact];
contact.name = @"5";
[self.contacts addObject:contact];
contact.name = @"6";
[self.contacts addObject:contact];
contact.name = @"7";
[self.contacts addObject:contact];
}
我有 1 个部分
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
// Return the number of sections.
return 1;
}
我有数组中的行数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// Return the number of rows in the section.
return [self.contacts count];
}
我在这里创建我的细胞
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
ContactTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ContactCell"];
Contact *contact = [self.contacts objectAtIndex:[indexPath row]];
cell.contactNameLabel.text = contact.name;
return cell;
}
所以我不确定为什么每个表格单元格标签都显示“7” 提前谢谢你
最佳答案
在viewDidLoad
- (void)viewDidLoad {
self.contacts = [NSMutableArray arrayWithCapacity:10];
Contact *contact = [[Contact alloc] init];
contact.name = @"1";
[self.contacts addObject:contact];
//Create new instance of Contact
contact = [[Contact alloc] init];
contact.name = @"2";
[self.contacts addObject:contact];
//Add objects same in way
}
如果没有创建新对象 [[Contact alloc] init]
,那么您正在更改同一个对象。
关于iOS TableView 在每个单元格中显示相同的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23820833/