swift – UITableViewCell:圆角和阴影
我正在改变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的回答
这个问题来得很愉快!我自己也完全解决了同样的问题.
>在单元格的内容视图中创建一个UIView(让我们将其称为mainBackground).这将包含您所有单元格的内容.在Storyboard中定位并应用必要的约束. 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中设置阴影的所有属性.请记住在故事板中更改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,height: 8)).cgPath self.layer.shouldRasterize = true self.layer.rasterizationScale = UIScreen.main.scale } } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |