我正在更改 UITableViewCell 的宽度,以便单元格更小,但用户仍然可以沿 tableview 的边缘滚动。
override func layoutSubviews() {
// Set the width of the cell
self.bounds = CGRectMake(self.bounds.origin.x, self.bounds.origin.y, self.bounds.size.width - 40, self.bounds.size.height)
super.layoutSubviews()
}
然后我绕过角落:
cell.layer.cornerRadius = 8
cell.layer.masksToBounds = true
到目前为止一切都很好。问题发生在影子上。边界被遮盖了,所以阴影显然不会出现。我查找了其他答案,但似乎无法弄清楚如何沿着边界圆角和显示阴影。
cell.layer.shadowOffset = CGSizeMake(0, 0)
cell.layer.shadowColor = UIColor.blackColor().CGColor
cell.layer.shadowOpacity = 0.23
cell.layer.shadowRadius = 4
那么我的问题 – 如何同时减小宽度、圆角并向 UITableViewCell 添加阴影?
更新:尝试 R Moyer 的回答
最佳答案
这个问题来得正是时候!我真的只是自己解决了同样的问题。
- 在单元格的内容 View 中创建一个
UIView
(我们将其称为mainBackground
)。这将包含您单元格的所有内容。将其定位并在 Storyboard 中应用必要的约束。 - 创建另一个
UIView
。这一个将是带有阴影的那个(我们将其称为shadowLayer
)。完全按照您对mainBackground
的方式放置它,但在它后面,并应用相同的约束。 现在您应该可以按如下方式设置圆角和阴影:
cell.mainBackground.layer.cornerRadius = 8 cell.mainBackground.layer.masksToBounds = true cell.shadowLayer.layer.masksToBounds = false cell.shadowLayer.layer.shadowOffset = CGSizeMake(0, 0) cell.shadowLayer.layer.shadowColor = UIColor.blackColor().CGColor cell.shadowLayer.layer.shadowOpacity = 0.23 cell.shadowLayer.layer.shadowRadius = 4
但是,这里的问题是:计算每个单元格的阴影是一项缓慢的任务。当您滚动浏览表格时,您会注意到一些严重的延迟。解决此问题的最佳方法是为阴影定义 UIBezierPath
,然后对其进行栅格化。所以你可能想这样做:
cell.shadowLayer.layer.shadowPath = UIBezierPath(roundedRect: cell.shadowLayer.bounds, byRoundingCorners: .AllCorners, cornerRadii: CGSize(width: 8, height: 8)).CGPath
cell.shadowLayer.layer.shouldRasterize = true
cell.shadowLayer.layer.rasterizationScale = UIScreen.mainScreen().scale
但这又产生了一个新问题! UIBezierPath
的形状取决于 shadowLayer
的边界,但在调用 cellForRowAtIndexPath
时边界未正确设置。因此,您需要根据 shadowLayer
的边界调整 shadowPath
。最好的方法是子类化 UIView
,并向 bounds 属性添加一个属性观察器。然后在didSet
中设置阴影的所有属性。请记住更改 Storyboard 中的 shadowLayer
类以匹配您的新子类。
class ShadowView: UIView {
override var bounds: CGRect {
didSet {
setupShadow()
}
}
private func setupShadow() {
self.layer.cornerRadius = 8
self.layer.shadowOffset = CGSize(width: 0, height: 3)
self.layer.shadowRadius = 3
self.layer.shadowOpacity = 0.3
self.layer.shadowPath = UIBezierPath(roundedRect: self.bounds, byRoundingCorners: .allCorners, cornerRadii: CGSize(width: 8, height: 8)).cgPath
self.layer.shouldRasterize = true
self.layer.rasterizationScale = UIScreen.main.scale
}
}
关于swift - UITableViewCell : rounded corners and shadow,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37645408/