Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UITableViewCell column width change based on screen orientation IOS Swift

I need to make below table like structure in one of the apps I am developing. I am creating this table using UITableView & I need my table column width to change based on the screen orientation. I have set constraints for column width & I will assign values to these using the screen width in my viewDidLoad().

However, I am not able to figure out how to re-align these constraints when screen orientation changes. I figured out that viewWillTransition() will be called when orientation is changed & I recalculated the constraints inside that & called setNeedsLayout() for the table view. However, I am not able to make my table view to reset the table column width when screen orientation is changed. I am new to IOS platform and any help will be greatly appreciated.

HDR_parName/HDR_parValue/HDR_minValue/HDR_maxValue

Para1/value1/minvalue1/maxvalue1

Para2/value2/minvalue2/maxvalue2

like image 557
Arun Sreekumar Avatar asked Jan 31 '23 01:01

Arun Sreekumar


2 Answers

override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
    super.viewWillTransitionToSize(size, withTransitionCoordinator: coordinator)

    let animationHandler: ((UIViewControllerTransitionCoordinatorContext) -> Void) = { [weak self] (context) in
        // This block will be called several times during rotation, 
        // so if you want your tableView change more smooth reload it here too. 
        self?.tableView.reloadData()
    }

    let completionHandler: ((UIViewControllerTransitionCoordinatorContext) -> Void) = { [weak self] (context) in
        // This block will be called when rotation will be completed
        self?.tableView.reloadData()
    }

    coordinator.animateAlongsideTransition(animationHandler, completion: completionHandler)

}

Then tableView datasource and delegate methods will be called, where you can setup elements size according to tableView frame size.

like image 142
Alex Sh. Avatar answered Feb 04 '23 05:02

Alex Sh.


Swift 4

override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
    super.viewWillTransition(to: size, with: coordinator)

    let animationHandler: ((UIViewControllerTransitionCoordinatorContext) -> Void) = { [weak self] (context) in
        // This block will be called several times during rotation,
        // so if you want your tableView change more smooth reload it here too.
        self?.yourTable.reloadData()
    }

    let completionHandler: ((UIViewControllerTransitionCoordinatorContext) -> Void) = { [weak self] (context) in
        // This block will be called when rotation will be completed
        self?.yourTable.reloadData()
    }

    coordinator.animate(alongsideTransition: animationHandler, completion: completionHandler)

}
like image 33
Heki Avatar answered Feb 04 '23 06:02

Heki