Ben*_*ash 0 iphone cocoa-touch objective-c uitableview nsarray
我目前正在构建一个iPhone应用程序,它将显示来自名为"故事"的NSMutableArray的数据.数组结构如此(通过NSLog):
2009-07-20 12:38:30.541 testapp[4797:20b] (
{
link = "http://www.testing.com";
message = "testing";
username = "test";
},
{
link = "http://www.testing2.com";
message = "testing2";
username = "test2";
} )
Run Code Online (Sandbox Code Playgroud)
我的cellForRowAtIndexPath目前看起来像这样:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease];
}
for (NSDictionary *story in stories) {
[cell setTextColor:[UIColor whiteColor]];
[cell setFont: [UIFont systemFontOfSize:11]];
cell.text = [NSString stringWithFormat:[story objectForKey:@"message"]];
}
return cell;
}
Run Code Online (Sandbox Code Playgroud)
目前,我的UITableView显示了SAME项的多个条目(恰好是数组中的最终集).如何让它成功遍历数组并一个接一个地在单元格中显示下一个项目的消息.
提前致谢 :)
石磊
您误解了cellForRowAtIndexPath:方法的工作原理.
您拥有它的方式,您创建一个单元格,然后重复重置其text,textColor和字体属性,然后返回单个单元格.
理解您的问题的关键是理解cellForRowAtIndexPath:被多次调用,对于将在屏幕上显示的每个单元格一次.所以不是你的for()循环,而是这样做:
NSDictionary * story = [stories objectAtIndex:[indexPath row]];
[cell setTextColor:[UIColor whiteColor]];
[cell setFont: [UIFont systemFontOfSize:11]];
cell.text = [NSString stringWithFormat:[story objectForKey:@"message"]];
Run Code Online (Sandbox Code Playgroud)
传入的indexPath参数是tableView如何指示它要求您的单元格.我们用它从你的数组中获取相应的故事字典.
编辑:
我还想指出这段代码不兼容iPhone OS 3.0.3.0 SDK引入了UITableViewCell工作方式的变化,包括其视图层次结构.你可能想成为接入小区的为textLabel,然后设置的特性是,像这样的:
NSDictionary * story = [stories objectAtIndex:[indexPath row]];
[[cell textLabel] setTextColor:[UIColor whiteColor]];
[[cell textLabel] setFont: [UIFont systemFontOfSize:11]];
[[cell textLabel] setText:[NSString stringWithFormat:[story objectForKey:@"message"]]];
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9098 次 |
| 最近记录: |