更改dataSource后,UITableView无法正确刷新

时间:2010-01-14 18:48:45

标签: iphone uitableview

我有一个带有多个数据源的UITableView。这是因为,我需要使用UISegmentedControl切换数据,如果我将它们添加为子视图,我就不能使用statusBar向上滚动等。

首先,我会显示一个登录屏幕:

self.tableView.dataSource = loginTableView;
self.tableView.delegate = loginTableView;
[self.tableView reloadData];

然后,一旦用户登录,我将执行以下操作以更改为index:1的segmentedControler,这是他们的个人资料:

self.tableView.dataSource = profileTableView;
self.tableView.delegate = profileTableView;
[self.tableView reloadData];

但是,表视图更新,但两个dataSource之间有点混合。一些文本已经改变,一些是重叠的,而一些文本完全缺失。

我是否应该为UITableView更改dataSource?

THX

6 个答案:

答案 0 :(得分:9)

我遇到了完全相同的问题。我的解决方案是使tableView隐藏,更改它的源代码,重新加载数据并使tableView再次可见。

C#(MonoTouch)中的示例:

tableView.Hidden = true;
tableView.Source = newTableViewSource;
tableView.ReloadData();
tableView.Hidden = false;

答案 1 :(得分:4)

不确定为什么会发生这种情况。

不要更改委托和数据源,而是替换ivar代表正在显示的数据的任何内容:

- (NSArray*)tableData{

    if(showingLogin)
        return self.loginData;

    return self.profileData;
}

现在你只有1个UITableViewController实例,但是一个BOOL告诉你要使用哪个数据源。

答案 2 :(得分:2)

表视图在内部缓存用于显示数据的单元格。因此,如果您更改数据源,您还应检查您的 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath方法是将所有单元格更新为正确的新值。

从您的描述中可以看出它正在使用缓存的UITableViewCell实例,并且在所有情况下都没有将其更新为正确的新数据。也许是这样的代码:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil)
    {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
        cell.frame = CGRectZero;
        cell.textLabel.font = //Set font;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.textLabel.text = @"My Text for this cell"; // <==== Not good! Move it out of this if block
    }
    // Set cell text here
}

我发现这类问题的最简单的解决方案是根据数据源生成用于创建单元格的String(CellIdentifier)。在这种情况下,您不要混合不同内容类型的单元格(如果单元格需要具有不同的外观,这也会对您有所帮助,具体取决于模式)。

答案 3 :(得分:1)

我有这个问题,原来是因为我的CellIdentifiers是一样的......

static NSString *CellIdentifier = @"Cell";

更改其中一个并正确布置单元格

static NSString *CellIdentifier2 = @"Cell2";

答案 4 :(得分:0)

哇,这太怪异了。

我最后一次做这样的事情时,我只是使用多个视图,隐藏一个视图并在分割控件被点击时显示另一个视图。还有其他可能的解决方案,但这可能是最简单的,也许是最有效的。

答案 5 :(得分:0)

我有同样的问题,你要做的是在- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath中使用不同的小区标识符。

if (self.segmentedControl.selectedSegmentIndex == 0) {
    self.cellIdentifier = @"segmentOne";
} else {
    caseAtIndexPath = [self.awaitingReviewCaseList caseAtIndex:indexPath.row];
    self.cellIdentifier = @"segmentTwo";
}
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:self.cellIdentifier forIndexPath:indexPath];
相关问题