ios 在xcode中添加shadow来分隔单元格文件?

yk9xbfzb  于 2023-07-01  发布在  iOS
关注(0)|答案(1)|浏览(127)

我已经为tableView的单元格分离了.xib.swift文件。我试图添加一些阴影周围的细胞,这里是我的代码与阴影剪下增加。这是行不通的,但我不确定如何以另一种方式实现它

class ShopHistoryCell: UITableViewCell {
    @IBOutlet weak var shopName: UILabel!
    @IBOutlet weak var departureDate: UILabel!
    @IBOutlet weak var arrivalDate: UILabel!
    @IBOutlet weak var carClass: UILabel!
    @IBOutlet weak var rewardText: UILabel!
    @IBOutlet weak var imageView1: UIImageView!
    @IBOutlet weak var imageView2: UIImageView!

    var delegate: ShopHistoryCellProtocol?
    
    var recentShops: [ShopHistorySearch]? {
        didSet {
        }
    }
    private var shopViews: [ShopView]? = []
    
    //padding
    override var frame: CGRect {
        get {
            return super.frame
        }
        set {
            var frame = newValue
            frame.origin.x += 20
            frame.size.width -= 2 * 20
            frame.origin.y += 10
            frame.size.height -= 2 * 10
            super.frame = frame
        }
    }

    override func awakeFromNib() {
        super.awakeFromNib()
        setupShadow()
        
    }
    
    func setupShadow() {
        layer.masksToBounds = false
        layer.shadowColor = UIColor.black.cgColor
        layer.shadowOpacity = 0.5
        layer.shadowOffset = CGSize(width: 0, height: 2)
        layer.shadowRadius = 4
        layer.shadowPath = UIBezierPath(rect: bounds).cgPath
        layer.shouldRasterize = true
        layer.rasterizationScale = UIScreen.main.scale
    }
}

下面是.xib文件树(单元格)

vx6bjr1n

vx6bjr1n1#

要使用单独的.xib和.swift文件向自定义UITableViewCell添加阴影效果,您需要确保阴影应用到正确的图层。在这种情况下,您可以将阴影应用于单元格的contentView。下面是代码的更新版本,它将阴影效果添加到单元格的contentView中:

func setupShadow() {
    contentView.layer.masksToBounds = false
    contentView.layer.shadowColor = UIColor.black.cgColor
    contentView.layer.shadowOpacity = 0.5
    contentView.layer.shadowOffset = CGSize(width: 0, height: 2)
    contentView.layer.shadowRadius = 4
    contentView.layer.shouldRasterize = true
    contentView.layer.rasterizationScale = UIScreen.main.scale
}

此外,setupShadow()函数也被修改为将阴影属性应用于contentView,而不是单元格的主层。类似地,在layoutSubviews()方法中调用updateShadowPath()函数,以便在布局更改时更新阴影路径。

override func layoutSubviews() {
    super.layoutSubviews()
    updateShadowPath()
}

    func updateShadowPath() {
    contentView.layer.shadowPath = UIBezierPath(rect: contentView.bounds).cgPath
}

相关问题