更新时间:2022-11-16 07:54:46
好的。这不是UITableView的工作方式。当表视图需要绘制一个单元格(即一行)时;它会在 dataSource
属性中指定的对象上调用 tableView:cellForRowAtIndexPath:
。从该方法返回UITableViewCell是您的工作。这就是Apple的做法(以及应该如何做):
Okay. That's not how UITableView works. When the table view needs to draw a cell (ie, a row); it invokes tableView:cellForRowAtIndexPath:
on the object specified in the dataSource
property. It's your job to return a UITableViewCell from that method. This is how Apple does it (and how you should do it):
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"AnIdentifierString"];
if (cell == nil)
{
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"AnIdentifierString"] autorelease];
}
cell.textLabel.text = @"This text will appear in the cell";
return cell;
}
该方法的调用次数取决于其中的节数表视图和每个节中的行数。该过程如下:
The number of times that method will be invoked depends on the number of sections in the table view and the number of rows in each section. The process works like this:
numberOfSectionsInTableView:
其 dataSource
(它知道它实现了该方法,因为 dataSource
必须遵守 UITableViewDataSource
协议。) numberOfSectionsInTableView:
返回大于零的数字,则表视图将调用委托数据源
上的方法 tableView:numberOfRowsInSection:
。因此,如果 numberOfSectionsInTableView:
返回 2
,则 tableView:numberOfRowsInSection:
tableView:numberOfRowsInSection:
都返回一个大于零的数字,则表视图将调用在 dataSource
上使用委托方法 tableView:cellForRowAtIndexPath:
'因此,如果 tableView:numberOfRowsInSection:
返回 5
, tableView:numberOfRowsInSection:
将被调用五次(每行一次) 。 indexPath
变量): cell.textLabel.text = [someArrayYouHave objectAtIndex:indexPath.row];
。numberOfSectionsInTableView:
on its dataSource
(it knows it implements that method because the dataSource
must adhere to the UITableViewDataSource
protocol).numberOfSectionsInTableView:
returns a number greater than zero, the table view will invoke the delegate method tableView:numberOfRowsInSection:
on the dataSource
. So if numberOfSectionsInTableView:
returns 2
, tableView:numberOfRowsInSection:
will be invoked twice.tableView:numberOfRowsInSection:
returns a number greater than zero, the table view will invoke the delegate method tableView:cellForRowAtIndexPath:
on the dataSource
' So if tableView:numberOfRowsInSection:
returns 5
, tableView:numberOfRowsInSection:
will be invoked five times (once for each individual row).indexPath
variable): cell.textLabel.text = [someArrayYouHave objectAtIndex:indexPath.row];
.