Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Putting a custom view into a UITableView

I have a regular-style UITableView—the one that has a white background and gray horizontal lines to separate the rows.

I have another custom UIView that is just a 100x100 rectangle filled with redColor.

How can I put the latter into the former, such that it appears over the horizontal lines, but is still a “part” of the table view in the sense that when I scroll the table view around, the red view scrolls with it? In fact, I should also be able to put my finger on the red area and scroll the table view.

Once again, if the red view is placed to overlap some horizontal lines, it should appear over the lines. Sadly, when I just add the red view as a subview to the table view, the horizontal lines go over the red view; see this screenshot.

How can this be accomplished?

like image 549
Enchilada Avatar asked Jan 30 '12 16:01

Enchilada


1 Answers

The correct place to handle the stacking order of your red square is in the layoutSubviews method. The table view sends itself layoutSubviews any time it adds or removes subviews (and at other times).

You need to make a subclass of UITableView that has a reference to the red square:

@interface MyTableView : UITableView

@property (weak, readonly) IBOutlet UIView *redSquare;

@end

You can initialize redSquare in whatever way you want. I just put it in my nib along with the table view, and moved it to be a subview of the table view in awakeFromNib:

@implementation MyTableView

@synthesize redSquare = _redSquare;

- (void)awakeFromNib {
    [self addSubview:self.redSquare];
}

Anyway, to actually make sure the red square is always on top of the table cells and grid lines, override layoutSubviews like this:

- (void)layoutSubviews {
    [super layoutSubviews];
    [self bringSubviewToFront:self.redSquare];
}
like image 106
rob mayoff Avatar answered Oct 27 '22 22:10

rob mayoff