简体   繁体   中英

UITableView in UIView in UIScrollView. When scrolling tableview and scroll scrollview too

I want to make when tableView scroll and scrollView will scroll.

I know have a solution is that use the delegate that when the tableView scroll and make the scrollView contentOfSet change but that is I don't want.

UITableView in UIView in UIScrollView. When scrolling tableview don't scroll scrollview too

Just like this article, I think is without any setting only initialize the view, anyone can tell me to achieve this?

Here is how I initialize view:

import UIKit

class ViewController: UIViewController {
    
    let backView = UIScrollView()
    let tableView = UITableView()
    let testView = UIView()

    override func viewDidLoad() {
        super.viewDidLoad()
        
        view.addSubview(backView)
        backView.frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height)
        backView.contentSize = CGSize(width: UIScreen.main.bounds.width, height: 1000)
        
        backView.addSubview(testView)
        testView.frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 500)
        
        testView.addSubview(tableView)
        tableView.frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 500)
        
        tableView.dataSource = self        
        
    }

}

extension ViewController: UITableViewDataSource {
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 50
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = UITableViewCell()
        cell.textLabel?.text = "\(indexPath.row)"
        return cell
    }
    
}

If you want multiple scrollviews(tableview/scrollview) in a hierarchy then you should make the inner scrollview unscrollable.

In your case the tableview should have height equal to its content's height so that it will no more be scrollable. But the parent scrollview will help in scrolling. That will prevent scrolling conflicts.

Use ContentSizesTableView in place of TableView.

class ContentSizedTableView: UITableView {
    override var contentSize: CGSize {
        didSet{
            self.invalidateIntrinsicContentSize()
        }
    }

    override var intrinsicContentSize: CGSize {
        self.layoutIfNeeded()
        return contentSize
    }

    override func reloadData() {
        super.reloadData()
        invalidateIntrinsicContentSize()
        layoutIfNeeded()
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM