Skip to content

Instantly share code, notes, and snippets.

@vgrichina
Created November 12, 2012 21:39
Show Gist options
  • Star 12 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save vgrichina/4062103 to your computer and use it in GitHub Desktop.
Save vgrichina/4062103 to your computer and use it in GitHub Desktop.
Customizable background view for UITableViewCell in grouped table view
//
// CellBackgroundView.h
//
//
#import <UIKit/UIKit.h>
typedef enum {
CellPositionTop,
CellPositionMiddle,
CellPositionBottom,
CellPositionSingle
} CellPosition;
@interface CellBackgroundView : UIView
@property(assign) CellPosition position;
@property(strong) UIColor *fillColor;
@property(strong) UIColor *borderColor;
@end
//
// CellBackgroundView.m
//
//
#import "CellBackgroundView.h"
static const CGFloat kCornerRadius = 10;
@implementation CellBackgroundView
@synthesize position, fillColor, borderColor;
- (void)drawRect:(CGRect)rect
{
CGRect bounds = CGRectInset(self.bounds,
0.5 / [UIScreen mainScreen].scale,
0.5 / [UIScreen mainScreen].scale);
UIBezierPath *path;
if (position == CellPositionSingle) {
path = [UIBezierPath bezierPathWithRoundedRect:bounds cornerRadius:kCornerRadius];
} else if (position == CellPositionTop) {
bounds.size.height += 1;
path = [UIBezierPath bezierPathWithRoundedRect:bounds
byRoundingCorners:UIRectCornerTopLeft | UIRectCornerTopRight
cornerRadii:CGSizeMake(kCornerRadius, kCornerRadius)];
} else if (position == CellPositionBottom) {
path = [UIBezierPath bezierPathWithRoundedRect:bounds
byRoundingCorners:UIRectCornerBottomLeft | UIRectCornerBottomRight
cornerRadii:CGSizeMake(kCornerRadius, kCornerRadius)];
} else {
bounds.size.height += 1;
path = [UIBezierPath bezierPathWithRect:bounds];
}
[self.fillColor setFill];
[self.borderColor setStroke];
[path fill];
[path stroke];
}
@end
@vgrichina
Copy link
Author

Comment above has typo CellPositingSingle should be CellPositionSingle

@frantovar
Copy link

Nice!

@rolandjitsu
Copy link

There is one thing missing though: [path addClip];. Sometimes you may get a black background under the corner radius, I tired a lot of things before I discovered that doing the just mentioned fixes it. I could not find an explanation why though :| And with latest XCode, there is no need to @synthesize anymore, the compiler does that for you runtime.

@performat
Copy link

Still very useful today. Thanks a lot!

@susmita-fueled
Copy link

Thanks! This is very useful.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment