根据内容自动更改单元格高度 - Swift
问题描述:
在Swift中使用UITableView,有人可以帮我根据标签,图片和描述自动更改单元格的高度吗?
Using a UITableView in Swift, could someone please help me automatically change the height of the cell based on the label, picture, and description please?
所有的信息正确传递,我只需要帮助格式化它。
All of the information passes through correctly, I just need help formatting it.
我尝试使用 cell.frame.size.height $ c $进行调整c>,但那没有效果。我可以在故事板中更改单元格的大小,但如果可能的话,我希望它更具动态。
I tried adjusting it using cell.frame.size.height
, but that had no effect. I could change the size of the cell in the storyboard, but I would like it more dynamic if possible.
提前感谢您!
我的细胞如下所示:
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
}
答
为了使单元格自动变大,你需要做两件事:
In order to make the cell auto sizeable, you need to do two things:
- 使用autolayout来排列单元格内的元素。底部空间和顶部空间限制将根据需要推动单元格大小。
- 在 tableView.rowHeight = UITableViewAutomaticDimension c> viewDidLoad
- Use autolayout to arrange the elements inside of your cell. Bottom space and top space constraints will push the cell size as needed.
- Set
tableView.rowHeight = UITableViewAutomaticDimension
in yourviewDidLoad