用于包装标签静态表格单元格动态的高度?(Dynamic height for static tabl

2019-06-17 18:26发布

我的文字是两条线在纵向模式下长。 当我切换到横向模式,它适合成一行。 我通过一个故事板使用静态的tableview细胞; 我怎么可以调整该行紧贴?

屏幕是一个登入画面。

  • 第一个单元格中包含一些说明文字
  • 第二个是一个文本字段,输入帐户名
  • 第三是安全的文本字段中输入密码
  • 第四个(也是最后一次)单元格包含登入按钮。 键盘上的回车键提交表单或切换焦点,适当

Answer 1:

使用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和作为sizeWithFont方法在IOS 7.0弃用



Answer 2:

我有一点点简单的实现成功。 只要你的静态表视图对细胞的适当约束,你可以要求系统的大小为你:

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
}


Answer 3:

我已经得到了这个使用正确的约束条件在标签上有设置并返回UITableViewAutomaticDimension在heightForRowAt这样的顶部和底部约束工作

override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    return UITableViewAutomaticDimension
}

在我来说,我有几个标签堆栈视图中,我不得不设置堆栈视图顶部和底部的内容查看为了使细胞生长。



文章来源: Dynamic height for static table cells with wrapping labels?