我想分享我的解决方案:
这需要您继承 UITableView 并添加一个属性,为了演示,我们将其称为 showShadow。将此添加到表视图的 .h 文件中:
@property (nonatomic,assign) BOOL showShadow;
及其对应的.m文件中的@synthesize来创建getter和setter方法:
@synthesize showShadow;
然后将 iVar UIView *shadowView; 添加到表视图的 .h 文件中。
现在在子类 UITableView 的 - (id)initWithFrame:(CGRect)frame 方法中添加以下代码来设置最终将投射阴影的视图:
- (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;
}
最后,编写 setter 方法来显示/隐藏阴影:
-(void)setShowShadow:(BOOL)s{
showShadow = s;
if(s){
[self.superview insertSubview:shadowView belowSubview:self];
}else{
[shadowView removeFromSuperview];
}
}
此外,如果您想移动表格(无论出于何种原因),您应该重写 -setFrame: 方法以同时移动 shadowView(因为它不在表格视图的视图层次结构中):
-(void)setFrame:(CGRect)frame{
[super setFrame:frame];
shadowView.frame = frame;
}
您已成功启用阴影!像这样使用它:
MySubclassedTableView *table = [[MySubclassedTableView alloc]initWithFrame:CGRectMake(20, 200, 280, 200)];
[self.view addSubview:table];
table.showShadow = YES;
警告:
您必须设置 showShadow 属性 AFTER 添加表格视图,因为行 table.showShadow 将调用行 [self.superview insertSubview:shadowView belowSubview:self];这需要表格视图存在。