Swift, Auto Resize Custom Table View Cells

2019-02-19 10:42发布

In my app, I have a table view with an image, label and text view in each cell. I would like to be able to auto-resize the cells depending on the amount of content in the text view. (The text view is the lower most text.)

So far, I have added the correct constraints; leading, trailing, top and bottom to the text view and have disabled scrolling and editing.

In my tableViewController.swift file, I have written this code:

override func viewWillAppear(_ animated: Bool) { tableView.estimatedRowHeight = 100 tableView.rowHeight = UITableViewAutomaticDimension }

However, this is not working as when I add more text to the text view, it just cuts off.

Maybe this has something to do with the card like look, I have got a UIView in each cell acting as a card.

I honestly don't know what I am doing wrong

A picture is below of what my app looks like and if anyone could help that would be greatly appreciated

enter image description here

4条回答
一纸荒年 Trace。
2楼-- · 2019-02-19 11:18

Update for swift 4.2

Use:

UITableView.automaticDimension

Instead of:

UITableViewAutomaticDimension
查看更多
The star\"
3楼-- · 2019-02-19 11:22

Make sure that the content mode is set to Scale To Fill of your UITextView Make sure that there are no height constraints for the UITextView and the card UIView

Try to add the estimated height into viewDidLoad:

override func viewDidLoad() {
    tableView.estimatedRowHeight = 100
    tableView.rowHeight = UITableViewAutomaticDimension
}

Maybe the AutoHeight is not working because of the UIView above the UITextView. Try to call the sizeToFit and layoutIfNeeded methods for the UIView in the cellForRowAt:

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Identifier", for: indexPath) as! CustomTableViewCell
cell.vwCard.sizeToFit()
cell.vwCard.layoutIfNeeded()
return cell
}

You can also try the sizeToFit and layoutIfNeeded as well for the UITextView.

Hope this works..

查看更多
趁早两清
4楼-- · 2019-02-19 11:25

Set bottom of your textView with bottom of that white UIView and make sure that white UIView has left,right,top and bottom constraints :)

Same type of example is explained here programmatically....

查看更多
爷的心禁止访问
5楼-- · 2019-02-19 11:37

Check if your constraints are like this(based on your image) :

imageView : set to Top and Leading of your container, with fix height and width values.

label : you can set it to top and horizontal space of your image, with fix height and width as well.

textView : leading to image, top space to label, trailing and bottom to container.

And keep using

tableView.estimatedRowHeight = 100
        tableView.rowHeight = UITableViewAutomaticDimension

in your viewWillAppear()

查看更多
登录 后发表回答