包装标签的静态表格单元格的dynamic高度?

我的文本是纵向模式下的两行。 当我切换到横向模式时,它适合于一条线。 我通过故事板使用静态tableview单元格; 我怎么能调整行适合贴合?

屏幕是一个login屏幕。

  • 第一个单元格包含一些说明文字
  • 第二个是input帐户名称的文本字段
  • 第三个是用于input密码的安全文本字段
  • 第四个(也是最后一个)单元格包含loginbutton。 键盘上的返回键提交表格或根据需要切换焦点

使用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]; } } 

编辑 :添加了对> and < ios7 support> and < ios7在iOS 7.0中不推荐使用sizeWithFont方法

我已经成功了一个简单的实现。 只要您的静态表格视图对单元格有适当的限制,您可以要求系统为您resize:

 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 }