在编程填充的TableView中没有刷新屏幕

时间:2012-04-23 08:06:34

标签: iphone objective-c ios tableview

当我再次向下滚动时,tableView中的文本将消失。

enter image description here enter image description here

我的代码是:

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    return [screenDefBuild.elementsToTableView count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *MyIdentifier = @"MyIdentifier";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:MyIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:MyIdentifier];
    }

    ScreenListElements *currentScreenElement = [screenDefBuild.elementsToTableView objectAtIndex:indexPath.row];
    cell.textLabel.text = currentScreenElement.objectName;

    currentRow++;    
    return cell;
}
- (void)viewDidLoad
{
    [super viewDidLoad];
    tableView = [[UITableView alloc] initWithFrame:self.view.bounds];
    [tableView setDataSource:self];
    [self.view addSubview:tableView];
}

我还希望将我的表视图填充到整个屏幕。 (顶部的灰色表带)。

2 个答案:

答案 0 :(得分:2)

我不知道你对这个变量做了什么

currentRow++;

但无论你使用哪种方式,我都会打赌它会破坏你的代码。

每当一个单元格即将出现在屏幕上时,UITableView都会调用cellForRowAtIndexPath,无论之前是否已经在屏幕上显示。当您向下滚动然后向上滚动时,此变量将超出数据范围,因此您将获得空单元格。

您需要设计此方法,以便可以随时在表视图中创建任何单元格。您不能依赖单元格的制作顺序,滚动时您必须反复制作相同的单元格。只能使用indexPath来确定您当前应该制作的单元格。

http://developer.apple.com/library/ios/#documentation/UIKit/Reference/UITableView_Class/Reference/Reference.html

答案 1 :(得分:0)

回答问题的第二部分 - 灰色表带。您正在将表视图添加到当前视图,因此您应该使用self.view.frame的size属性,而不是原点。您希望将其设置为0,0。

更改

tableView = [[UITableView alloc] initWithFrame:self.view.bounds];

CGRect viewFrame=self.view.frame;
viewFrame.origin=CGPointZero;
tableView = [[UITableView alloc] initWithFrame:viewFrame]; 

至于你问题的第一部分 - 这很奇怪,因为你似乎正确地做了一切。我可能建议的一件事是在[tableView reloadData];的末尾添加viewDidLoad