gpt4 book ai didi

iphone - 在 Landscape 中自动调整 UITableCells 内容

转载 作者:塔克拉玛干 更新时间:2023-11-02 07:52:23 24 4
gpt4 key购买 nike

在 UITableView 中,我通过 UILabel 将内容添加到我的单元格。

定义最佳尺寸(单元格宽度允许的最大尺寸) 我注意到只有 tableView.contentSize.width 是可靠的,因为 cell. contentView.bounds 始终提供纵向宽度,即使是横向

这与 autoresizingMask 配合使用非常有效:当我从纵向切换到横向然后再切换到纵向时。

当我直接在 Landscape 中加载我的 View 时会出现问题。我的 UILabel 的宽度大于屏幕,即使断点显示正确的宽度 tableView.contentSize.width

横向和纵向之间的切换没有任何变化,宽度仍然比屏幕大。

如果我不使用 autoresizingMask,宽度是正确的,如果我使用它,即使文本很短,它也会从屏幕上消失(但我注意到它只是由于测试背景颜色或使用非常大的 NSString ).

简而言之:

  • 纵向 > 横向 > 纵向 > 横向...很好(完美调整大小)
  • 横向 > 纵向 > 横向 > 纵向...错误(宽度超出范围)

我的代码简化了:

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{

//[...]
UIFont *font = [UIFont fontWithName:@"Helvetica-Bold" size:12.0];
CGRect frame = CGRectMake(cell.contentView.bounds.origin.x + 20,
cell.contentView.bounds.origin.y + 4,
tableView.contentSize.width - 50,
font.lineHeight);

//at this point a breakpoint shows that frame is whatever I asked (ex: 200 for test)
//but still the labels is wider than the screen
UILabel *result = [[[UILabel alloc] initWithFrame:frame] autorelease];
[result setText:@"bouh!"];
result.lineBreakMode = UILineBreakModeWordWrap;
result.numberOfLines = 1;
result.font = font;

//if I comment this line, the width is always what I want
result.autoresizingMask = UIViewAutoresizingFlexibleWidth;

//test to see the real size
result.backgroundColor = [UIColor orangeColor];

[cell.contentView addSubview:result];
//[...]
return cell;
}

我在这里请求你的帮助,看看是否有更好的方法来做我想做的事情?如果不是,我做错了什么?

最佳答案

我找不到一个干净简单的通用解决方案(适用于每个屏幕)。

但这是我为使其工作所做的工作:

    //in portrait cell width works fine with autoResize
//in landscape tableView width works fine with autoResize
CGFloat cellWidth;

if ( [UIDevice currentDevice].orientation != UIDeviceOrientationLandscapeLeft
&& [UIDevice currentDevice].orientation != UIDeviceOrientationLandscapeRight)
{
cellWidth = tableView.contentSize.width;
}
else
{
cellWidth = cell.contentView.bounds.size.width;
}

因此,稍后在代码中我会这样使用它:

CGRect frame = CGRectMake(cell.contentView.bounds.origin.x + 20,
cell.contentView.bounds.origin.y + 4,
cellWidth - 50,
font.lineHeight);
UILabel *result = [[[UILabel alloc] initWithFrame:frame] autorelease];

但有些事情很奇怪:我需要始终使用 tableView.contentSize.width 作为我的 Activity Indicators 的框架,因为 cell.contentView.bounds.size.width 是即使在风景中也只有 320

CGRect activityIndicatorRect =
CGRectMake(
cell.contentView.bounds.origin.x + tableView.contentSize.width - 60 ,
cell.contentView.bounds.origin.y + 17,
30, 30);

关于iphone - 在 Landscape 中自动调整 UITableCells 内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6105489/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com