Search code examples
iosswiftuitableviewautolayout

Adjusting custom Tableviewcell - NSLayoutConstraint conflict. UIView-Encapsulated-Layout-Height


I am having a problem with autolayout Programmatically.I am adjusting a tableviewCell with a custom UIView.The uiView have an image inside with no issues.I am getting this error.What am doing wrong here?

(
    "<NSLayoutConstraint:0x6000034e0e10 V:|-(1)-[XKCD_Comics.CardView:0x7f932b610f80]   (active, names: '|':UITableViewCellContentView:0x7f932b6085c0 )>",
    "<NSLayoutConstraint:0x6000034e1a90 XKCD_Comics.CardView:0x7f932b610f80.bottom == UITableViewCellContentView:0x7f932b6085c0.bottom - 1   (active)>",
    "<NSLayoutConstraint:0x6000034e2120 XKCD_Comics.CardView:0x7f932b610f80.height == 310   (active)>",
    "<NSLayoutConstraint:0x6000034e1590 'UIView-Encapsulated-Layout-Height' UITableViewCellContentView:0x7f932b6085c0.height == 312.5   (active)>" )

Will attempt to recover by breaking constraint  <NSLayoutConstraint:0x6000034e2120 XKCD_Comics.CardView:0x7f932b610f80.height == 310   (active)>

Contstraints

func createViewHierarchy() {
        //Initialize constaints Array
        var constraints = [NSLayoutConstraint]()
        
        //Setting up constraint for UIVIEW - ComicsView
        constraints.append(comicsUIVIew.topAnchor.constraint(equalTo: self.contentView.topAnchor, constant: 10))
        constraints.append(comicsUIVIew.leadingAnchor.constraint(equalTo: self.contentView.leadingAnchor, constant: 10))
        constraints.append(comicsUIVIew.trailingAnchor.constraint(equalTo: self.contentView.trailingAnchor, constant: -10))
        constraints.append(comicsUIVIew.bottomAnchor.constraint(equalTo: self.contentView.bottomAnchor, constant: -10))
        constraints.append(comicsUIVIew.heightAnchor.constraint(equalToConstant: 310))

        //activate NSLayoutconstaints
        NSLayoutConstraint.activate(constraints)
        
    }

Solution

  • Table views can end up with non-whole-number heights due to the way cell separators are rendered.

    So, on a device with @2x screen scale, your comicsUIVIew height will end up at 310.5 ... on a @3x device, it will be 310.333

    If that's acceptable, you can avoid the auto-layout complaints by changing the Priority on your height constraint:

        //constraints.append(comicsUIVIew.heightAnchor.constraint(equalToConstant: 310))
    
        let hc = comicsUIVIew.heightAnchor.constraint(equalToConstant: 310)
        hc.priority = .defaultHigh
        constraints.append(hc)
        
    

    If you need comicsUIVIew to be exactly 310 points, you can add a clear "spacer" view (or a UILayoutGuide) below comicsUIVIew, giving it a height constraint of 0.0 with priority of .defaultHigh. It will end up being 0.5 or 0.333 points tall.

    Or... set tableView.separatorStyle = .none, and design your cell to have a "bottom border line" to simulate the separator if desired.