Author Topic: How to center a table view vertically in a view  (Read 10063 times)

kjmcneish

  • Administrator
  • *****
  • Posts: 719
    • View Profile
How to center a table view vertically in a view
« on: April 23, 2015, 10:52:30 PM »
To center a table view vertically in a view, create the following extension of the UITableViewController class:

Code: [Select]
extension UITableViewController {
   
    func centerTableView() {
       
        let contentSize = self.tableView.contentSize
        let boundsSize = self.tableView.bounds.size
       
        if contentSize.height < boundsSize.height {
           
            var yOffset = floor(boundsSize.height - contentSize.height) / 2
           
            tableView.contentOffset = CGPointMake(0, -yOffset)
        }
    }
}

In your table view controller, add the following override of viewWillLayoutSubviews:

Code: [Select]
override func viewWillLayoutSubviews() {
        self.centerTableView()
}

Now when your table view will be centered in the scene at run time.

All the best!
Kevin McNeish
Author of Learn to Code in Swift: https://itunes.apple.com/us/book/learn-to-code-in-swift/id942956811?mt=11
« Last Edit: September 05, 2015, 03:39:12 PM by kjmcneish »