根据内容自动更改单元格高度 – Swift

在Swift中使用UITableView,有人可以请帮我自动改变基于标签,图片和描述的单元格的高度吗?

所有的信息都正确传递,我只需要帮助格式化它。

我试着调整它使用cell.frame.size.height ,但是没有效果。 我可以改变故事板中单元格的大小,但是如果可能的话,我希望它更具dynamic性。

先谢谢你!

我的单元格如下:

 override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! UITableViewCell // Creator let creator = self.photos[indexPath.row].creator let user = UILabel() user.frame = CGRectMake(self.headerView.frame.origin.x, self.headerView.frame.origin.y + self.headerView.frame.height + 3, self.view.frame.width, 12) user.text = creator cell.addSubview(user) // Photo let picture = self.photos[indexPath.row].image() let imageView = UIImageView(image: picture!) imageView.frame = CGRectMake(user.frame.origin.x, user.frame.origin.y + user.frame.height, self.view.frame.width, 400) imageView.contentMode = UIViewContentMode.ScaleAspectFit cell.addSubview(imageView) // Photo description let description = UITextView() let des = self.photos[indexPath.row].photoDescription description.frame = CGRectMake(imageView.frame.origin.x, imageView.frame.origin.y + imageView.frame.height, self.view.frame.width, 65) if des != nil { description.text = des! description.font = UIFont.systemFontOfSize(16) description.editable = false description.scrollEnabled = false } cell.addSubview(description) cell.frame.size.height = user.frame.size.height + imageView.frame.size.height + description.frame.size.height + 30 return cell } 

为了使单元尺寸变大,你需要做两件事情:

  1. 使用自动布局来排列单元格内的元素。 底部空间和顶部空间限制将根据需要推动单元大小。
  2. viewDidLoad设置tableView.rowHeight = UITableViewAutomaticDimension

如果您的单元格高度依赖于文本大小,请按照下列步骤操作:在ViewController.swift中添加该方法

 func calculateHeight(inString:String) -> CGFloat { let messageString = inString let attributes : [String : Any] = [NSFontAttributeName : UIFont.systemFont(ofSize: 15.0)] let attributedString : NSAttributedString = NSAttributedString(string: messageString, attributes: attributes) let rect : CGRect = attributedString.boundingRect(with: CGSize(width: 222.0, height: CGFloat.greatestFiniteMagnitude), options: .usesLineFragmentOrigin, context: nil) let requredSize:CGRect = rect return requredSize.height } 

设置文本标签宽度然后调用这个函数:

  func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { heightOfRow = self.calculateHeight(inString: conversations[indexPath.row].description) return (heightOfRow + 60.0) } 

对于基本单元格:

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

此function对于自定义单元格不起作用。

如果您的单元格高度取决于图像高度 ,则返回图像高度+ someFloatValueAccordingToYourChoice。

希望它能工作。