Is it possible to use AutoLayout with UITableView's tableHeaderView?

前端 未结 29 1342
醉梦人生
醉梦人生 2020-11-28 19:51

Since I discovered AutoLayout I use it everywhere, now I\'m trying to use it with a tableHeaderView.

I made a subclass of

29条回答
  •  -上瘾入骨i
    2020-11-28 20:40

    Here's what works for UITableViewController in ios 12,

    Drap a UIView into the TableView above all the prototype cells for header and below all the prototype cells for footer. Setup your header and footer as needed. Set all the required constraints.

    Now use the following extension methods

    public static class UITableVIewExtensions
    {
    
        public static void MakeHeaderAutoDimension(this UITableView tableView)
        {
            if (tableView.TableHeaderView is UIView headerView) {
                var size = headerView.SystemLayoutSizeFittingSize(UIView.UILayoutFittingCompressedSize);
                if (headerView.Frame.Size.Height != size.Height) {
                    var frame = headerView.Frame;
                    frame.Height = size.Height;
                    headerView.Frame = frame;
                    tableView.TableHeaderView = headerView;
                    tableView.LayoutIfNeeded();
                }
            }
        }
    
        public static void MakeFooterAutoDimension(this UITableView tableView)
        {
            if (tableView.TableFooterView is UIView footerView) {
                var size = footerView.SystemLayoutSizeFittingSize(UIView.UILayoutFittingCompressedSize);
                if (footerView.Frame.Size.Height != size.Height) {
                    var frame = footerView.Frame;
                    frame.Height = size.Height;
                    footerView.Frame = frame;
                    tableView.TableFooterView = footerView;
                    tableView.LayoutIfNeeded();
                }
            }
        }
    }
    

    and call it in ViewDidLayoutSubviews of the subclass of UITableViewController

    public override void ViewDidLayoutSubviews()
    {
        base.ViewDidLayoutSubviews();
    
        TableView.MakeHeaderAutoDimension();
        TableView.MakeFooterAutoDimension();
    }
    

提交回复
热议问题