iosuitableviewnstablecellview

Constraint UITableViewCell, wrong rightAnchor


I need to constraint a UITableViewCell programmatically via Code... I am trying to create a sub view inside the cell's containerView, this is the Actual code :

contentView.addSubview(testContainerView)

testContainerView.leftAnchor  .constraint(equalTo: contentView.leftAnchor  , constant: 8).isActive = true
testContainerView.topAnchor   .constraint(equalTo: contentView.topAnchor   , constant: 0).isActive = true
testContainerView.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: 0).isActive = true
testContainerView.rightAnchor .constraint(equalTo: contentView.rightAnchor , constant: 8).isActive = true

But the problem is that the cell's width seems to exceed the screen size... I have never had this issue before. The cell are created using this method:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "slotCell") as! SlotTableViewCell2
    cell.setCellDetail(currentSlot: listaSlots[indexPath.row])

    return cell
}

Is there anything wrong with the constraints?

This is an image of the current result :

The orange rect, is the testContainerView


Solution

  • You are using the wrong constant for the rightAnchor.

    Try the following code:

    contentView.addSubview(testContainerView)
    NSLayoutConstraint.activate([
        testContainer.leftAnchor.constraint(equalTo: contentView.leftAnchor, constant: 8.0)
        testContainer.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 0.0)
        testContainer.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: 0.0)
        testContainer.rightAnchor.constraint(equalTo: contentView.rightAnchor, constant: -8.0)
    ])
    

    Notice the negative constant on the rightAnchor.

    Extra hint: The Autolayout Engine loves knowing about all constraints before activating them. Using the above-shown method is the preferred way to configure constraints

    Extra hint 2: If your App is used by any RightToLeft Language Interface, it will be flipped. Rather use leadingAnchor & trailingAnchor instead of leftAnchor & rightAnchor if this is not the intended behaviour