简体   繁体   中英

Updating UITableViewCell subview constraints on orientation change

I have a UITableView with 3 cells, which will eventually serve as a dashboard. I am trying to configure the top cell with a circular progress view using KDCircularProgress - I have a UIView which I position with constraints, and then programmatically add the circular progress object.

However, when I rotate the device to landscape, the progress view shifts (see first image). I have tried various combinations of setNeedsLayout() , layoutSubviews and layoutIfNeeded() but no luck.

I also tried reloadData() in willAnimateRotation(to toInterfaceOrientation: UIInterfaceOrientation, duration: TimeInterval) , which gets me slightly further in that the view is correctly resized (see second image), however it has created a duplicate. Extract from cellForRowAt method below:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    switch indexPath.row {
    case 0:
        let topCell = tableView.dequeueReusableCell(withIdentifier: "topCell", for: indexPath) as! DashboardTopTableViewCell

        //Progress config
        topCell.progressBar = KDCircularProgress(frame: CGRect(origin: CGPoint.zero, size: CGSize(width: topCell.circularProgressContainer.frame.width, height: topCell.circularProgressContainer.frame.height)))
        let colorForProgress: UIColor = UIColor(red: 69.0/255.0, green: 110.0/255.0, blue: 178.0/255.0, alpha: 0.8)
        topCell.progressBar?.progressColors = [colorForProgress]
        let progressAsAngle = ((percentageComplete/100)*360)
        topCell.progressBar?.animate(toAngle: progressAsAngle, duration: 2.0, completion: nil)
        topCell.circularProgressContainer.addSubview(topCell.progressBar!)

        return topCell

So I am a bit stuck - any suggestions?

在此处输入图片说明

在此处输入图片说明

Avoid using addSubview in cellForRow. As the cell is reused, this extra added view will not get removed and on reloading cell, the views would be overlapped. You will not see the impact when overlapping is of same size and position, but as in your case you are rotating, you are able to see it. Add the views statically in XIb or view wherever you want but not in cellForRowAt.

However you can change the properties of the subviews in cellForRow.

If you add subviews in cellForRowAt you will feel the jerk while scrolling tableView.

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