I've a plain UITableView (not grouped) that I want to add a dropshadow to left and to the right.
How can I achieve this? I've tried:
[self.tableView.layer setShadowColor:[[UIColor whiteColor] CGColor]];
[self.tableView.layer setShadowOffset:CGSizeMake(0, 0)];
[self.tableView.layer setShadowRadius:5.0];
[self.tableView.layer setShadowOpacity:1];
but it doesn't work.
You need to make sure clipsToBounds
and masksToBounds
are set to NO
on the view and layer respectively.
self.tableView.clipsToBounds = NO;
self.tableView.layer.masksToBounds = NO;
I would like to share my solution: This requires you to subclass UITableView and add a property, for the sake of demonstration let's call it showShadow. Add this to your table view's .h file:
@property (nonatomic,assign) BOOL showShadow;
and its corresponding @synthesize in the .m file to create getter and setter methods:
@synthesize showShadow;
Then add an iVar UIView *shadowView;
to the table view's .h file.
Now in the - (id)initWithFrame:(CGRect)frame
method of your subclassed UITableView add the following piece of code to set up the view that will eventually cast the shadow:
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
shadowView = [[UIView alloc]initWithFrame:self.frame];
shadowView.backgroundColor = [UIColor whiteColor];
shadowView.layer.shadowOpacity = 0.1;
shadowView.layer.shadowOffset = CGSizeMake(3, 3);
shadowView.layer.shadowRadius = 1;
}
return self;
}
And, finally, write the setter method to show/hide the shadow:
-(void)setShowShadow:(BOOL)s{
showShadow = s;
if(s){
[self.superview insertSubview:shadowView belowSubview:self];
}else{
[shadowView removeFromSuperview];
}
}
Additionally if you would like to move the table (for whatever reason), you should override the -setFrame:
method to also move the shadowView along with it (as it is not in the table view's view hierarchy):
-(void)setFrame:(CGRect)frame{
[super setFrame:frame];
shadowView.frame = frame;
}
You have successfully enabled shadows ! Use it like this :
MySubclassedTableView *table = [[MySubclassedTableView alloc]initWithFrame:CGRectMake(20, 200, 280, 200)];
[self.view addSubview:table];
table.showShadow = YES;
WARNING:
You have to set the showShadow property AFTER you add your table view, because the line table.showShadow will call the line [self.superview insertSubview:shadowView belowSubview:self]; which requires the table view to be existent.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With