将阴影添加到UITableView

Fre*_*ins 16 iphone objective-c shadow uitableview

我有一个简单的UITableView(未分组),我想在左侧和右侧添加一个Drophadow.

在此输入图像描述

我怎样才能做到这一点?我试过了:

[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];
Run Code Online (Sandbox Code Playgroud)

但它不起作用.

mat*_*way 49

你需要确保clipsToBoundsmasksToBounds设置为NO分别对视图和层.

self.tableView.clipsToBounds = NO;
self.tableView.layer.masksToBounds = NO;
Run Code Online (Sandbox Code Playgroud)

  • 谢谢(你的)信息.但是如果我设置tableView.layer.masksToBounds = NO; &tableView.clipsToBounds = NO; ,我的tableviewcell移动到tableviews的上方.我在viewController中有tableview,imageview.因此,某些部分由表视图使用,而某些部分由iamgeview使用.你能帮帮我吗? (5认同)
  • 你最好把UIView放在UITableView后面并将阴影添加到UIView. (3认同)

the*_*tic 5

我想分享我的解决方案:这需要您继承UITableView并添加一个属性,为了进行演示,我们将其称为showShadow。将此添加到表视图的.h文件中:

@property (nonatomic,assign) BOOL showShadow;

及其在.m文件中的相应@synthesize,以创建getter和setter方法:

@synthesize showShadow;

然后将iVar添加UIView *shadowView;到表视图的.h文件中。现在,在- (id)initWithFrame:(CGRect)frame您的子类UITableView 的方法中,添加以下代码来设置最终将产生阴影的视图:

- (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;
}
Run Code Online (Sandbox Code Playgroud)

最后,编写setter方法以显示/隐藏阴影:

-(void)setShowShadow:(BOOL)s{

    showShadow = s;

    if(s){
        [self.superview insertSubview:shadowView belowSubview:self];
    }else{
        [shadowView removeFromSuperview];
    }
}
Run Code Online (Sandbox Code Playgroud)

另外,如果您要移动表(出于某种原因),则应重写该-setFrame:方法以同时将shadowView与它一起移动(因为它不在表视图的视图层次结构中):

-(void)setFrame:(CGRect)frame{

     [super setFrame:frame];
     shadowView.frame = frame;

}
Run Code Online (Sandbox Code Playgroud)

您已成功启用阴影!像这样使用它:

MySubclassedTableView *table = [[MySubclassedTableView alloc]initWithFrame:CGRectMake(20, 200, 280, 200)];
        [self.view addSubview:table];
        table.showShadow = YES;
Run Code Online (Sandbox Code Playgroud)

警告:

你必须设置showShadow属性你把你的表视图,因为该行table.showShadow将调用线[self.superview insertSubview:shadowView belowSubview:自我]。这要求表视图存在。