如何只为边框添加阴影?

时间:2018-12-24 04:20:10

标签: ios swift

我想在collectionview单元格周围添加阴影。但是阴影在单元格中的图像和标签周围,单元格周围没有阴影。有人知道如何解决吗?

    cell.contentView.layer.cornerRadius = 2.0
    cell.contentView.layer.borderWidth = 1.0
    cell.contentView.layer.borderColor = UIColor.clear.cgColor
    cell.contentView.layer.masksToBounds = true

    cell.layer.masksToBounds = false
    cell.layer.shadowColor = UIColor.black.cgColor
    cell.layer.shadowOpacity = 0.5
    cell.layer.shadowOffset = CGSize(width: -1, height: 1)
    cell.layer.shadowRadius = 1

Shadow around the content(not the border)

3 个答案:

答案 0 :(得分:2)

您直接将阴影应用于import random import math circle_x = 500 circle_y = 500 a = random.randint(0,500) * 2 * math.pi r = 1 * math.sqrt(random.randint(0,500)) x = r * math.cos(a) + circle_x y = r * math.sin(a) + circle_y ,因此它不起作用。您需要在contentView内部进行查看,将所有内容放入该视图中,并从各个角度进行填充(例如8pt)。

假设我已将此视图命名为contentView,然后:

vwContainer

如果您要实现其他界面,请使用图片更新您的问题。

答案 1 :(得分:1)

extension UIView {
    func addShadow(color: UIColor, radius: CGFloat = 1, offset: CGSize) {
        self.layoutIfNeeded()
        self.layer.masksToBounds = false
        self.layer.shadowColor = color.cgColor
        self.layer.shadowOpacity = 0.5
        self.layer.shadowOffset = offset
        self.layer.shadowRadius = radius
        self.layer.shadowPath = UIBezierPath(rect: self.bounds).cgPath
    }
}

用作:

let offset = CGSize(width:-1,height:1)

cell.addShadow(color:.black,offset:offset)

答案 2 :(得分:0)

您需要如下设置contentView的背景颜色

cell.contentView.backgroundColor = .white