如何在旋转时更改UITableViewController的外观?

时间:2011-09-10 20:16:28

标签: iphone objective-c rotation uitableview

我目前正在尝试使用UITableViewController执行的任务是在纵向模式下使用单列单元格行,在横向模式下使用双列单元格行。它只是为了方便观看(使用可用的宽度空间来查看更多的行 - 单元格),因此两个列单元的格式相同。但是,我不确定如何实现它。

所以,我的想法是在“cellForRowAtIndexPath”方法中使用我的单元格自定义内容并检查当前的屏幕模式。问题是我是否必须在“shouldAutorotateToInterfaceOrientation”中设置一些标志,或者有一些设置?

第二,只是在“shouldAutorotateToInterfaceOrientation”中调用表重新加载才能重新绘制表格的单元格吗?

另外,我正在考虑制作不同的笔尖并在IB中设计我的细胞。我想这是另一个问题,只是想知道这会如何影响解决方案。

2 个答案:

答案 0 :(得分:1)

您必须检查cellForRowAtIndexPath中的当前方向并正确配置您的手机。您可以使用IB创建2个不同的单元格。

此外,您必须在其中一个回调中调用[myTableView reloadData]轮换事件(shouldAutorotateToInterfaceOrientation didRotateFromInterfaceOrientation)。每次拨打cellForRowAtIndexPath(所有小区)时,都会调用[myTableView reloadData]。 请确保使用不同的标识符重复使用单元格。

编辑:这是我编写代码的方式:

将2个IBOutlets添加到.h文件中:

IBOutlet MyCustomCell1 * customCell1;
IBOutlet MyCustomCell2 * customCell2;

在Interface Builder中,设置每个单元格的标识符属性,可能类似于cellIdentifier1cellIdentifier2。确保IB中文件的所有者是您的dataSource(实现cellForRowAtIndexPath的地方)。

cellForRowAtIndexPath应如下所示:

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if ([UIDevice currentDevice].orientation == UIDeviceOrientationLandscapeLeft 
    || [UIDevice currentDevice].orientation == UIDeviceOrientationLandscaperight) 
    {
         //Landscape, lets use MyCustomCell2.
         NSString * cellIdentifier2 = @"cellIdentifier2";

         MyCustomCell2 * cell  = (MyCustomCell2 *) [tableView dequeueReusableCellWithIdentifier:cellIdentifier];

         if (cell == nil) {
         //We have to initialize the cell, we're going to use IB
         [[NSBundle mainBundle] loadNibNamed:@"CustomCell2NibName" owner:self options:nil];
         //After this, customCell2 we defined in .h is initialized from IB 
         cell = customCell2;

         }
         //setup the cell, set text and everything.

         return cell;
    }

    else
    {
    //portrait case, the same as before but using CustomCell1
    NSString * cellIdentifier1 = @"cellIdentifier1";

         MyCustomCell1 * cell  = (MyCustomCell1 *) [tableView dequeueReusableCellWithIdentifier:cellIdentifier];

         if (cell == nil) {
         //We have to initialize the cell, we're going to use IB
         [[NSBundle mainBundle] loadNibNamed:@"CustomCell1NibName" owner:self options:nil];
         //After this, customCell1 we defined in .h is initialized from IB 
         cell = customCell1;

         }
         //setup the cell, set text and everything.

         return cell;


     }

}

答案 1 :(得分:1)

tableView:cellForRowAtIndexPath:的代码中,您可以使用以下方法检查当前方向:

if (self.interfaceOrientation == UIInterfaceOrientationPortrait ||
    self.interfaceOrientation == UIInterfaceOrientationPortraitUpsideDown) {
    // use a portrait cell
} else {
    // use a landscape cell
}

另外,请务必从YES返回shouldAutorotateToInterfaceOrientation:。您还应该在tableView之后使用didRotateFromInterfaceOrientation:重新加载[tableView reloadData];,以确保正在使用正确的单元格。

相关问题