UIScrollview的内容大小不会随着自动布局而增加

时间:2019-01-05 09:28:46

标签: ios swift uitableview uiscrollview autolayout

我已经添加了一个UIScrollView,并且想要添加4个等于屏幕大小的UITableView。因此,scrollview将有4页等于屏幕大小。我在scrollview中添加了一个内容视图,并在其中添加了4个表视图,但是由于其内容大小没有增加,所以我无法进行垂直滚动。

以下是我的xib:

enter image description here

蓝色区域是内容视图,但是宽度没有增加,尽管当我使用页面控件移动滚动视图时,我可以看到其他表格视图。

1 个答案:

答案 0 :(得分:1)

首先,给定tableview的静态高度,并使用此高度出口。下一步是,您需要观察tableview以获取高度,然后在该观察器中分配您可以分配每个tableview的高度。

 override func viewWillAppear(_ animated: Bool) {
     Tblvw1.addObserver(self, forKeyPath: "contentSize", options: [.new], context: nil)
     Tblvw2.addObserver(self, forKeyPath: "contentSize", options: [.new], context: nil)
     Tblvw3.addObserver(self, forKeyPath: "contentSize", options: [.new], context: nil)
     Tblvw4.addObserver(self, forKeyPath: "contentSize", options: [.new], context: nil)
}

 override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)        
        Tblvw1.removeObserver(self, forKeyPath: "contentSize")
        Tblvw2.removeObserver(self, forKeyPath: "contentSize")
        Tblvw3.removeObserver(self, forKeyPath: "contentSize")
        Tblvw4.removeObserver(self, forKeyPath: "contentSize")      

    }

   override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        if object is UITableView {
            print("contentSize:= \(Tblvw1.contentSize.height)")
            self.heightOfTable1.constant = Tblvw1.contentSize.height
            self.heightOfTable2.constant = Tblvw2.contentSize.height
            self.heightOfTable3.constant = Tblvw3.contentSize.height
            self.heightOfTable4.constant = Tblvw4.contentSize.height
        }
    }

注意:请确保您必须禁用所有表视图的滚动