旋转自定义UITableViewCell

时间:2010-03-19 12:40:10

标签: iphone uitableview rotation reusability initwithstyle

我有一个自定义UITableViewCell,它包含几个UIButtons。每个按钮的框架位置相对于单元格宽度。我设置了autoresizingMask = UIViewAutoresizingFlexibleWidth,因此当应用程序以横向或纵向模式启动时,它将正确调整单元格宽度和按钮位置。

问题是当设备从一种模式旋转到另一种模式时,按钮不会调整位置,因为UITableViewCell是可重复使用的。换句话说,基于新的UITalbeView宽度不会初始化单元格,因为在设备旋转之前调用单元格的函数initWithStyle,而在设备旋转之后不再调用该单元格。有什么建议吗?

6 个答案:

答案 0 :(得分:13)

由于UITableViewCell也是UIView,因此您可以覆盖setFrame方法。每次表视图旋转时,都会为所有单元格调用此方法。

-(void)setFrame:(CGRect)frame
{
    [super setFrame:frame];

    //Do your rotation stuffs here :)
} 

答案 1 :(得分:7)

经过数小时的研究(包括本网站的帖子)后,我找不到任何解决方案。但是一个灯泡突然开启了。解决方案非常简单。只需检测设备方向是横向还是纵向模式,并为每个设置定义具有不同名称的ReusableCellIdentifier。

static NSString*Identifier;

if ([UIDevice currentDevice].orientation!=UIDeviceOrientationLandscapeLeft && [UIDevice currentDevice].orientation!=UIDeviceOrientationLandscapeRight) {
                Identifier= @"aCell_portrait";
            }
            else Identifier= @"DocumentOptionIdentifier_Landscape";


    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:Identifier];

答案 2 :(得分:6)

以前的答案有一个严重的问题。 您应该使用[UIApplication sharedApplication] .statusBarOrientation而不是[UIDevice currebtDevice] .orientation,因为设备方向与接口方向无关 - 设备方向是基于加速度计的物理旋转。

答案 3 :(得分:2)

勾选的答案就像旧版iOS中的魅力一样。对于iOS 6.0,我使用了下一个代码:

static NSString *Identifier;
if (self.interfaceOrientation==UIInterfaceOrientationPortrait) {
    Identifier=@"aCell_portrait";
}
else {
    Identifier=@"DocumentOptionIdentifier_Landscape";
}

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:Identifier];

答案 4 :(得分:1)

您需要在cellForRowAtIndexPath方法中修复单元格框架宽度(假设纵向和横向模式下的高度相同)。这就是在这里工作的。我曾经用IB创建一个自定义的TableViewCell,它总是初始化为纵向320像素宽度。通过定义框架,它可以按预期工作,即使从队列中“重用”单元格也是如此。

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
 ...
 UITableViewCell *cell = (UITableViewCell *)[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
 if (cell == nil) {
    // create cell here...
 }

 // Adjust cell frame width to be equal to tableview frame width
 cell.frame = CGRectMake(0, 0, tableView.frame.size.width, cell.frame.size.height);
 ...
}

答案 5 :(得分:0)

我有类似的问题,这篇文章帮助了我。在我的情况下,我在一个单独的文件中声明了一个自定义类,在这个文件中,我在layoutSubviews中有以下代码:

//PORTRAIT CELL
if ([UIDevice currentDevice].orientation!=UIDeviceOrientationLandscapeLeft && 
    [UIDevice currentDevice].orientation!=UIDeviceOrientationLandscapeRight)
{
    //build the custom content views for portrait mode here
}
else
{
    //build the custom content views for landscape mode here
}

然后在我的视图控制器中,我只实现willAnimateRotationToInterfaceOrientation:并将reloadData消息发送到我的表视图。

有了这个,我不必触及cellForRow方法。