user2606782
user2606782

Reputation: 320

UILabel shifts to the right when cell is tapped

I have a UITableView and have cells in it and I am using textLabel and detailTextLabel in it along with a accessoryView which is a disclosureIndicator. These are my constraints.

if (cell.contentView.constraints.count == 0) {
      cell.textLabel?.translatesAutoresizingMaskIntoConstraints = false
      cell.detailTextLabel?.translatesAutoresizingMaskIntoConstraints = false

      let margins = cell.contentView.layoutMarginsGuide

      // TextLabel constraints
      cell.textLabel?.leftAnchor.constraint(equalTo: margins.leftAnchor).isActive = true
      cell.textLabel?.centerYAnchor.constraint(equalTo: margins.centerYAnchor).isActive = true

      // DetailTextLabel constraints
      cell.detailTextLabel?.rightAnchor.constraint(equalTo: margins.rightAnchor, constant: -10).isActive = true
      cell.detailTextLabel?.leftAnchor.constraint(equalTo: (cell.textLabel?.layoutMarginsGuide.rightAnchor)!, constant: 10).isActive = true
      cell.detailTextLabel?.centerYAnchor.constraint(equalTo: margins.centerYAnchor).isActive = true
    }

Now when the Table View is first loaded I see everything fine i.e detailTextLabel is -10 points away from contentView but when I tap the cell the detailTextLabel shifts to the right and hugs to the contentView as if -10 point constraint isn't even there. Now when I come back to this VC again, I still see detailTextLabel hugging to contentView i.e reloadData is not taking any effect. But if I dismiss this VC and come back again here my constraint and in place like they should be and the problem comes up again when I tap on the cell to go to the next screen.

I have a reloadData() call in my viewWillAppear which gets called but doesn't produce any effect.

I hope I am able to explain myself, am I doing anything wrong here?

Upvotes: 0

Views: 164

Answers (2)

Kwaku Eshun
Kwaku Eshun

Reputation: 149

You cannot change the constraints of the cell labels if it is not a custom type cell. If you want custom constraints then you should create your own custom cell which inherits from UITableViewCell and set your own constraints.

Upvotes: 3

matt
matt

Reputation: 535121

The problem is that you are using a built in cell type, where the text label and detail label are built in and don’t belong to you. They belong to the cell. The cell repositions them on selection. You are fighting the cell.

If you want to customize a cell’s appearance and change the position of the cell labels, use a custom cell type, and give it custom labels that belong to you. You can given them constraints right in the storyboard designer. Do not use the built in text label and detail label at all.

Upvotes: 4

Related Questions