Horizontal UITableView

后端 未结 7 929
别跟我提以往
别跟我提以往 2020-11-27 13:34

I want implement a layout in my ipad application that has a uitable view that scrolls left and right rather then up and down :

So rather than

row 1 row 2 ro

7条回答
  •  鱼传尺愫
    2020-11-27 14:20

    There is a simple brilliant trick to get a UITableView to do both vertical and horizontal scroll perfectly.

    You can do it both with and without autolayout - I will explain it with autolayout.

    On you UITableView have a width constraint and no tailing alignment constraint. The bind this width constraint with an IBOutlet and in your controller set the following to properties on the table view.

    let contentWidth = 1000 // you calculate that
    tableViewWidthConstraint.constant = contentWidth
    tableView.contentSize.width = (contentWidth * 2) - UIScreen.main.bounds.size.width
    

    The tableview needs to be full width to render all the content in the horizontal direction, and the we plays with the content size compared with screen size that does the trick.

    The following locations of them below works but you can try the in different steps in the lifecycle:

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
    
        tableViewWidthConstraint.constant = contentWidth
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
    
        tableView.contentSize.width = (contentWidth * 2) - UIScreen.main.bounds.size.width
    }
    
    // and this is needed to support rotation:
    override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
            coordinator.animate(alongsideTransition: { (UIViewControllerTransitionCoordinatorContext) -> Void in
                self.tableView.contentSize.width = (contentWidth * 2) - UIScreen.main.bounds.size.width
            }, completion: nil)
        }
        super.viewWillTransition(to: size, with: coordinator)
    }
    

提交回复
热议问题