将阴影添加到UITableView

时间:2012-01-25 23:40:18

标签: iphone objective-c uitableview shadow

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

enter image description here

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

[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];

但它不起作用。

4 个答案:

答案 0 :(得分:48)

您需要确保clipsToBoundsmasksToBounds分别在视图和图层上设置为NO

self.tableView.clipsToBounds = NO;
self.tableView.layer.masksToBounds = NO;

答案 1 :(得分:4)

我想分享我的解决方案: 这需要您继承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(因为它不在表视图的视图层次结构中):< / p>

-(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];这要求表视图存在。

答案 2 :(得分:0)

白色的光芒不是我看到的影子吗?你没有偏移设置,所以它正是你想做的。对于阴影,将颜色设置为黑色,并给它一个偏差可能为3,5或者其他东西。

答案 3 :(得分:0)

添加@mattjgalloway提供的Swift版本的解决方案(对我很有帮助)

your_TableView.clipsToBounds = false
your_TableView..layer.masksToBounds = false
your_TableView..layer.shadowColor = UIColor.lightGray.cgColor
your_TableView..layer.shadowOffset = CGSize(width: 0, height: 0)
your_TableView..layer.shadowRadius = 5.0
your_TableView..layer.shadowOpacity = 0.5