UITableView的背景视图插入

时间:2018-06-09 18:56:09

标签: ios swift uitableview background scrollview

我需要将滚动视图显示为UITableView的背景视图。使用此代码(“constrain”方法是UIView类的扩展):

public class TestViewController: UITableViewController {

    public override func viewDidLoad() {

        // Disable scrolling od the tableview:
        self.tableView.isScrollEnabled = false;

        // Create the scrollview:
        let scrollview:UIScrollView = UIScrollView();
        scrollview.backgroundColor = UIColor.red;

        // Create a container that will contain all the subviews:
        let container:UIView = UIView();
        container.translatesAutoresizingMaskIntoConstraints = false;
        container.backgroundColor = UIColor.green;

        // Create the subviews (only one for the sample):
        let subView:UIView = UIView();
        subView.translatesAutoresizingMaskIntoConstraints = false;
        subView.backgroundColor = UIColor.blue;

        // Build the view hierarchy:
        container.addSubview(subView);
        scrollview.addSubview(container);
        self.tableView.backgroundView = scrollview;

        // Add the container constraints:
        scrollview.constrain(soThat: .top, of: container, is: .equal, to: .top, of: scrollview);
        scrollview.constrain(soThat: .bottom, of: container, is: .equal, to: .bottom, of: scrollview);
        scrollview.constrain(soThat: .left, of: container, is: .equal, to: .left, of: scrollview);
        scrollview.constrain(soThat: .right, of: container, is: .equal, to: .right, of: scrollview);
        scrollview.constrain(soThat: .width, of: container, is: .equal, to: .width, of: scrollview);

        // Add the subviews constraints:
        container.constrain(soThat: .top, of: subView, is: .equal, to: .top, of: container);
        container.constrain(soThat: .left, of: subView, is: .equal, to: .left, of: container, multiplier: 1, constant: 20);
        container.constrain(soThat: .width, of: subView, is: .equal, to: .width, of: container, multiplier: 1, constant: -40);
        subView.constrain(soThat: .height, of: subView, is: .equal, to: 1000);

        container.constrain(soThat: .bottom, of: subView, is: .equal, to: .bottom, of: container);

        // Needed on iOS to prevent the scrollview to be scrolled by 64px on startup:
        if #available(iOS 11.0, *) {
            scrollview.contentInsetAdjustmentBehavior = .always;
        }
    }
}

适用于iOS 11.“工作”是指:

  • 滚动视图的顶部位于导航栏的正下方
  • 启动时,子视图的顶部位于导航栏底部
  • 的正下方
  • 当我们滚动内容时,我们可以在导航栏下看到它

在iOS 9&如图10所示,滚动视图的顶部位于屏幕的顶部,位于导航栏下方。 TableView行在所有版本上都正确显示。

如何让后台视图适用于所有版本?

iOS 9& 10:

iOS 9 & 10

iOS 11:

iOS 11

0 个答案:

没有答案