前言
给 UITableView
同时设置圆角和阴影时发现在视图上只会显示圆角,原因是因为当我们设置 masksToBounds
为 YES
允许圆角剪裁时,圆角以外的阴影也会一并被剪裁掉。在网上找了一下解决方法,ios阴影圆角共存 这篇文章提供了一个思路,就是把圆角和阴影放在不同的两个控件上实现,然后叠加到一块。基本思路是正确的,但实际操作发现在最后插入作为阴影层的 CALayer
,调用的方法可能会照成层级有点混乱的问题。下面展示一下我解决这个问题的方法和用 Swift 实现的代码。
实现
上图,阴影设置的有点浅:
上代码:
Swift1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
| self.view_navigation.frame = CGRectMake(x: 61, y: 15, width: 261, height: CGFloat(50 * (model.navigaArr.count < 5 ? model.navigaArr.count : 5))) self.view_navigation.frame.origin.y += self.label_content.frame.height + self.label_content.frame.origin.y self.view_navigation.layer.cornerRadius = 14.0 self.view_navigation.layer.masksToBounds = true self.view_navigation.backgroundColor = UIColor.white self.view_navigation.reloadData()
let layer_navigation = CALayer() let frame_navigation = self.view_navigation.frame layer_navigation.name = "layer_navigation" layer_navigation.frame = frame_navigation layer_navigation.cornerRadius = 14.0 layer_navigation.backgroundColor = UIColor.white.cgColor layer_navigation.masksToBounds = false layer_navigation.shadowColor = UIColor.rgbaColorFromHex(rgb: 0x333333, alpha: 0.12).cgColor layer_navigation.shadowOffset = CGSize(width: 0, height: 2) layer_navigation.shadowOpacity = 1 layer_navigation.shadowRadius = 10
self.layer.insertSublayer(layer_navigation, at: 0)
|