我想将阴影设置为我的容器UIView。我使用下面的代码来实现:
- (id)initWithCoder:(NSCoder*)aDecoder
{
self = [super initWithCoder:aDecoder];
if (self) {
//-> drop shadow
[self.layer setShadowColor:[UIColor blackColor].CGColor];
[self.layer setShadowOpacity:0.6];
[self.layer setShadowRadius:2.0];
[self.layer setShadowOffset:CGSizeMake(2.0, 2.0)];
}
return self;
}这样做效果很好。但是,当我在这个容器UIView上使用_containerView.clipsToBounds = YES;时,我看不到我的影子。为什么?
发布于 2014-05-20 21:25:16
clipsToBounds还会剪辑您的阴影。为了防止这一点,你可以添加_containerView.layer.masksToBounds = NO,它禁止裁剪子层(参见更多here)。
发布于 2020-11-27 21:35:37
如果您因为不希望子视图超出视图的边界而不得不使用clipsToBounds = true,但同时又需要在视图上添加阴影,我建议在视图后面添加一个额外的视图,并在额外的视图上设置阴影属性。
//run this in viewDidLoad() or your initialisation code
private func setupShadowContainer() {
let containerShadow = UIView()
parentView.addSubview(containerShadow)
containerShadow.dropShadow()
//using SnapKit here, you can use NSLayoutConstraint in a similar way to constraint the containerShadow behind your View
containerShadow.snp.makeConstraints { (make) in
make.edges.equalTo(yourView.snp.edges)
}
}
//dropShadow method
extension UIView {
func dropShadow() {
self.translatesAutoresizingMaskIntoConstraints = false
self.layer.shadowRadius = 3
self.layer.shadowColor = UIColor.black.cgColor
self.layer.shadowOffset = CGSize(width: 1.0, height: 1.0)
self.layer.shadowOpacity = 0.5
self.layer.masksToBounds = false
}
}发布于 2019-10-17 22:40:53
下面是UIView扩展。
extension UIView {
func addShadowAndRoundCorner(cornerRadius : CGFloat) {
self.layer.shadowOffset = .zero
self.layer.shadowOpacity = 0.5
self.layer.shadowRadius = 3
self.layer.shadowColor = UIColor.black.cgColor
self.layer.masksToBounds = false
self.layer.cornerRadius = cornerRadius
}
}在创建view后调用此函数,如下所示:
let roundView = UIView()
roundView.frame = CGRect.init(x: 0, y: 0, width: 100, height: 100)
roundView.addShadowAndRoundCorner(cornerRadius: 100/2)https://stackoverflow.com/questions/23760918
复制相似问题