Search code examples
uitableviewswiftwidthcell

change width of tableviewcell swift


I have a tableView using IB with custom cells and prototype cells.

I'm trying to make the cells a little shorter in width than the tableView.frame to leave a little space between the left and right corners.

var cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as TableViewCell
        cell.bounds = CGRectMake(10, self.tableView.frame.origin.y, 30, self.tableView.frame.size.height)
        cell.layer.bounds = CGRectMake(10, self.tableView.frame.origin.y, 30, self.tableView.frame.size.height)
        cell.textLabel?.bounds = CGRectMake(10, self.tableView.frame.origin.y, 30, self.tableView.frame.size.height)

Update: here is a good example explaining how to add a subView to your tableView. http://natashatherobot.com/ios-frame-vs-bounds-resize-basic-uitableview-cell/

Update 2: Looks like there isn't an easy way to do this. There are 3 ways of achieving this as far as I know:

  1. Add a rounded and a shorter image to your cell that has the same exact color and matches your background.
  2. You could subclass tableViewCell and then play with the layoutSubviews, this way you can make it shorter before it draws the cell. I've done it but the scrolling performance sucks.
  3. The best way is to ditch the tableView altogether and re-do it with a collectionView.

Solution

  • The cells in the tableview are supposed to be as wide as their container.

    If you need your cells to have a different width than the table view, I would suggest adding a view as subview to cell.contentView and make that view as wide as you need while making sure the contentView has clear background and no separator and all (so that it appears it is not there).

    Another solution would be to have the tableView not as wide as it's superview by adding the left/right padding to it. But the you would have the issue that on the left and right side, where the padding is, you won't be able to scroll the tableView

    I consider the cleanest solution to use a collectionView. It is not that much different than a tableView and you can configure the entire size of the cell, not just the height.

    Hope this helps you fix your problem. Let me know if you need more help.