我的文字在纵向模式下是两行。当我切换到横向模式时,它适合单行。我通过故事板使用静态tableview单元格;我怎样才能调整行的大小以适应?
屏幕是一个登录屏幕。
答案 0 :(得分:9)
使用UITableView's heightForRowAtIndexPath
:
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
int topPadding = 10;
int bottomPadding = 10;
float landscapeWidth = 400;
float portraitWidth = 300;
UIFont *font = [UIFont fontWithName:@"Arial" size:22];
//This is for first cell only if you want for all then remove below condition
if (indexPath.row == 0) // for cell with dynamic height
{
NSString *strText = [[arrTexts objectAtIndex:indexPath.row]; // filling text in label
if(landscape)//depends on orientation
{
CGSize maximumSize = CGSizeMake(landscapeWidth, MAXFLOAT); // change width and height to your requirement
}
else //protrait
{
CGSize maximumSize = CGSizeMake(portraitWidth, MAXFLOAT); // change width and height to your requirement
}
//dynamic height of string depending on given width to fit
CGSize textSize = CGSizeZero;
if(SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"7.0")
{
NSMutableParagraphStyle *pstyle = [NSMutableParagraphStyle new];
pstyle.lineBreakMode = NSLineBreakByWordWrapping;
textSize = [[strText boundingRectWithSize:CGSizeMake(width, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName :font,NSParagraphStyleAttributeName:[pstyle copy]} context:nil] size];
}
else // < (iOS 7.0)
{
textSize = [strText sizeWithFont:font constrainedToSize:maximumSize lineBreakMode:NSLineBreakByWordWrapping]
}
return (topPadding+textSize.height+bottomPadding) // caculate on your bases as u have string height
}
else
{
// return height from the storyboard
return [super tableView:tableView heightForRowAtIndexPath:indexPath];
}
}
编辑:为support
添加了> and < ios7
,并且在iOS 7.0中弃用了sizeWithFont
方法
答案 1 :(得分:8)
我通过更简单的实施取得了成功。只要您的静态表视图对单元格有适当的约束,您就可以要求系统为您调整大小:
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat
{
let cell = self.tableView(self.tableView, cellForRowAtIndexPath: indexPath)
let height = ceil(cell.systemLayoutSizeFittingSize(CGSizeMake(self.tableView.bounds.size.width, 1), withHorizontalFittingPriority: 1000, verticalFittingPriority: 1).height)
return height
}
答案 2 :(得分:1)
我已经使用适当的约束来工作,其中标签设置了顶部和底部约束,并在heightForRowAt中返回UITableViewAutomaticDimension,如下所示
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return UITableViewAutomaticDimension
}
在我的情况下,我在堆栈视图中有几个标签,我不得不将堆栈视图的顶部和底部设置为contentView,以便单元格增长。