0

I'm a little confused where should I declare and how to add a subView to a cell to make the cell shorter in width.

I tried to use func viewWillLayoutSubviews(){} in my tableViewCell class but I can't access the tableView from there...weird..

What do I need to subclass for this to work and where do I need to insert this code?

Currently this code just adds a subview to the cell and kind of floats on top of the cell instead of containing the cell. I'm using it in cellForRowAtIndexPath.

  let testFrame : CGRect = cell.contentView.frame
    var testView : UIView = UIView(frame: testFrame)
    testView.backgroundColor = UIColor.redColor()
    testView.alpha=0.5
    testView.bounds = CGRectMake(cell.bounds.origin.x,
        cell.bounds.origin.y,
        cell.bounds.size.width - 50,
        cell.bounds.size.height);
    //TableViewCell.addSubview(testView)
    cell.contentView.addSubview(testView)
    return cell
Victor --------
  • 512
  • 1
  • 11
  • 29

1 Answers1

1

A subview is added inside of the cell, you are adding testView as a subview of the cell's content view. The frame of testView will be relative to the cell's content view (testView's superview).

It is not a good idea to change the width of UITableViewCell because there may be unintended side effects. You can override setFrame in a subclass of UITableViewCell which you return from cellForRowAtIndexPath:. More info here: How to set the width of a cell in a UITableView in grouped style

You should look at UICollectionView if you need cells that are not full width or make your table view the width you need.

Community
  • 1
  • 1
bjtitus
  • 4,231
  • 1
  • 27
  • 35
  • Hm, weird, I was able to do it for the tableView and make the entire tableView look shorter. With the cell though it just adds a red color subview on top of the cell view's content instead of actually the subview becoming the new cell. How can I make the cell be in the subview and not behind it ? – Victor -------- Mar 27 '15 at 20:05
  • You cannot put a cell in your own view. It is controlled by the `UITableView`. It sounds like you should review Apple's guide on Views, specifically Creating and Managing a View Hierarchy: https://developer.apple.com/library/ios/documentation/WindowsViews/Conceptual/ViewPG_iPhoneOS/CreatingViews/CreatingViews.html#//apple_ref/doc/uid/TP40009503-CH5-SW47 – bjtitus Mar 27 '15 at 20:08
  • could you please explain how is she able to it here then? http://natashatherobot.com/ios-frame-vs-bounds-resize-basic-uitableview-cell/ – Victor -------- Mar 27 '15 at 20:15
  • I can't explain in the comments any clearer than she has but instead of overriding setFrame: she is overriding layoutSubviews and changing the bounds instead of the frame (the bounds is the frame without the origin point, essentially). Both approaches are fragile and UICollectionView would be a better option. – bjtitus Mar 27 '15 at 20:20