UIScrollView高度是否不会根据视图大小动态更新?

时间:2018-11-01 06:36:06

标签: ios swift uitableview uiscrollview constraints

我有VC,在其中添加了UIScrollView-> UIView。之后,我添加了3个tableViews并添加了约束。基于动态调整大小的内容tableView,例如tbl1,tbl2和tbl3分别具有10、5和7行。基于内容,我想更新我的整个视图。此处 tableViews高度成功更新,但不是ScrollView

我的代码是...

override func viewDidLoad() {
    super.viewDidLoad()

    // Do any additional setup after loading the view.

    tbl1.delegate = self
    tbl1.dataSource = self
    tbl2.delegate = self
    tbl2.dataSource = self
    tbl3.delegate = self
    tbl3.dataSource = self
}

override func viewDidLayoutSubviews() {

    DispatchQueue.main.async {
        //Update tbl1 frame
        var frame = self.tbl1.frame
        frame.size.height = self.tbl1.contentSize.height
        self.tbl1.frame = frame
        //Update tbl2 frame
        var frame2 = self.tbl2.frame
        let y = self.tbl1.frame.maxY
        frame2.origin.y = y
        frame2.size.height = self.tbl2.contentSize.height
        self.tbl2.frame = frame2
        //Update tbl3 frame
        var frame3 = self.tbl3.frame
        let y2 = self.tbl2.frame.maxY
        frame3.origin.y = y2
        frame3.size.height = self.tbl3.contentSize.height
        self.tbl3.frame = frame3
    }

}

// MARK: - UITableView Delegates
func numberOfSections(in tableView: UITableView) -> Int {

    return 1
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    if tableView == tbl1 {
        return 10
    } else if tableView == tbl2 {
        return 5
    } else {
        return 7
    }
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    if tableView == tbl1 {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
        cell.textLabel?.text = "TBL ONE"

        return cell
    } else if tableView == tbl2 {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
        cell.textLabel?.text = "TBL TWO"

        return cell
    } else {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
        cell.textLabel?.text = "TBL THREE"

        return cell
    }

}

1 个答案:

答案 0 :(得分:1)

只需将此行添加到viewDidLayoutSubviews()的末尾

self.scrollView.contentSize.height = self.tbl1.contentSize.height + self.tbl2.contentSize.height + self.tbl3.contentSize.height