Created
November 12, 2012 21:39
-
-
Save vgrichina/4062103 to your computer and use it in GitHub Desktop.
Customizable background view for UITableViewCell in grouped table view
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// 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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// 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 |
Comment above has typo CellPositingSingle
should be CellPositionSingle
Nice!
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.
Still very useful today. Thanks a lot!
Thanks! This is very useful.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Sample usage: