【问题标题】:reloadData in a UITableView when deviceOrientation change当 deviceOrientation 改变时在 UITableView 中重新加载数据
【发布时间】:2011-04-14 14:37:34
【问题描述】:

我正在使用 UITableView 和 UITableViewCell。 我的应用支持横向,所以我创建了 2 个 UITableViewCell:一个用于纵向,一个用于横向。

在我的 cellForRowAtIndexPath 方法中,这是我的代码

static NSString *CellIdentifier;
static NSString *NibNamed;

UIDeviceOrientation deviceOrientation = [UIApplication sharedApplication].statusBarOrientation;

if (deviceOrientation != UIDeviceOrientationLandscapeLeft &&
    deviceOrientation != UIDeviceOrientationLandscapeRight)
{
    CellIdentifier= @"Cell1";
    NibNamed = @"cell_news";
}
else
{
    CellIdentifier= @"Cell2";
    NibNamed = @"cell_news_landscape";
}

[[NSBundle mainBundle] loadNibNamed:NibNamed owner:self options:NULL];
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];


if (cell == nil)
{
    NSArray *nib = [[NSBundle mainBundle] loadNibNamed:NibNamed owner:self options:nil];
    cell = [nib objectAtIndex:0];
}
///here i add title, description, ecc... in my UITableViewCell

然后在 shouldAutorotateToInterfaceOrientation 我写了这个:

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
[my_table reloadData];
return YES;
}

问题出在哪里? 如果我以纵向启动应用程序,当我第一次旋转设备时,什么也不会发生(并且 UITableCellView 是 Portrait_table_cell)。当我第二次旋转设备时(我处于纵向或倒置状态),我看到了landscape_table_cell(当然,我看不到所有文本,因为它从屏幕上消失了)。 所以.. 除了第一次,我旋转设备的其他时间,我看到了错误的 table_cell_view!!

你知道为什么吗? 谢谢!

【问题讨论】:

    标签: iphone uitableview landscape


    【解决方案1】:

    您的数据在设备改变方向之前重新加载。 shouldAutorotateToInterfaceOrientation 在任何旋转之前调用。

    试试 didRotateFromInterfaceOrientation

    - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation{
     [my_table reloadData];
    }
    

    还要注意 Jhaliya 给出的答案,因为该解决方案会比重新加载 tableview 更好。 如果数据源已更改,您应该只重新加载 tableview。

    【讨论】:

    • 但是看看@Jhaliya 怎么说。最好让细胞自动适应尺寸。
    【解决方案2】:

    不从shouldAutorotateToInterfaceOrientation调用reloadData:

    当您为 UITableViewUITableViewCell 创建对象时,请使用 UIView autoresizingMask 属性。因为UITableView andUITableViewCellare the subclass ofUIView`。

    @property(nonatomic) UIViewAutoresizing autoresizingMask
    

    【讨论】:

      【解决方案3】:

      我认为有两个问题。 1) shouldAutoRotateToInterfaceOrientation 在视图旋转之前被调用,所以如果你刷新,那就太早了。 2)我认为您需要自己管理重绘,而不是依赖 reloadData。因此,要么覆盖 tableViewCell 的重绘方法,要么适当地设置自动调整大小的掩码。希望这可以帮助。 -迈克

      【讨论】:

        【解决方案4】:

        如果自动调整大小不适合您,您还可以使用

        获取可见单元格索引

        - (NSArray *)indexPathsForVisibleRow

        然后用

        获取单元格本身

        - (UITableViewCell *)cellForRowAtIndexPath:(NSIndexPath *)indexPath

        并调用类似的方法

        [cell interfaceOrientationDidChangeTo:interfaceOrientation]

        让工作由细胞自己完成。

        【讨论】:

          猜你喜欢
          • 2015-08-01
          • 1970-01-01
          • 1970-01-01
          • 2023-03-31
          • 2014-04-23
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多