Dynamic UITableView height

后端 未结 11 1565
無奈伤痛
無奈伤痛 2020-12-29 09:47

I would like to set the UITableView to match the height for all the contents in the table view.

This is my storyboard

The problem with this is the t

相关标签:
11条回答
  • 2020-12-29 09:57

    Try this also

    in ViewDidLoad
    
     self.table.estimatedRowHeight = 44.0 ;
    self.table.rowHeight = UITableViewAutomaticDimension;
    

    Height for row at index path

    -(float)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return UITableViewAutomaticDimension;}
    
    0 讨论(0)
  • 2020-12-29 09:59

    Update Swift 4 this code working be good

    self.scrollView.layoutIfNeeded()
    self.view.layoutIfNeeded()
    self.tableViewHeightConstraint.constant = CGFloat(self.tableView.contentSize.height)
    
    0 讨论(0)
  • Based on solution @nikans, written in Xamarin

    [Register(nameof(DynamicSizeTableView)), DesignTimeVisible(true)]
    public class DynamicSizeTableView : UITableView
    {
        public override void LayoutSubviews()
        {
            base.LayoutSubviews();
            if (Bounds.Size != IntrinsicContentSize)
                InvalidateIntrinsicContentSize();
        }
    
        public override CGSize IntrinsicContentSize => ContentSize;
    
        public DynamicSizeTableView(CGRect frame) : base(frame) { }
    
        public DynamicSizeTableView(IntPtr handle) : base(handle) { }
    }
    
    0 讨论(0)
  • 2020-12-29 10:02

    Based on solution of @rr1g0

    Updated for Swift 5 in 2020, and works with TableViews with sections too.

    Create height constraint for tableView and create an outlet to it. And in viewDidLayoutSubviews() use the code below:

    var tableViewHeight: CGFloat = 0
    
    for section in 0..<tableView.numberOfSections {
        for row in 0..<tableView.numberOfRows(inSection: section) {
            tableViewHeight += tableView(tableView, heightForRowAt: IndexPath(row: row, section: section))
        }
    }
    
    tableViewHeightConstraint.constant = tableViewHeight
    
    0 讨论(0)
  • 2020-12-29 10:06

    In this type of case add your bottom imageView(red) in a table footer view.

    To add footer view in UITableView you can use:

    tableViewObj.tableFooterView = footerViewObj;
    
    0 讨论(0)
  • 2020-12-29 10:07

    Update for Swift 5. Adding maxHeight so that you can specify how tall you want your tableView to be

    class SelfSizingTableView: UITableView {
        var maxHeight = CGFloat.infinity
    
        override var contentSize: CGSize {
            didSet {
                invalidateIntrinsicContentSize()
                setNeedsLayout()
            }
        }
    
        override var intrinsicContentSize: CGSize {
            let height = min(maxHeight, contentSize.height)
            return CGSize(width: contentSize.width, height: height)
        }
    }
    
    0 讨论(0)
提交回复
热议问题