Adding rounded corner and drop shadow to UICollectionViewCell

前端 未结 15 2666
逝去的感伤
逝去的感伤 2020-12-12 09:50

So I already went through various posts on adding 2nd view for adding shadow, but I still cannot get it to work if I want to add it in UICollectionViewCell. I s

15条回答
  •  清歌不尽
    2020-12-12 10:44

    Here's my take on the solution. It's similar to other answers, with one key difference. It doesn't create a path that's dependent on the bounds of the view. Anytime you create a path based on the bounds and provide it to the layer you can run into issues when it's resizing, and need to setup methods to update the path.

    A simpler solution is to avoid using anything that is bounds dependent.

    let radius: CGFloat = 10
    
    self.contentView.layer.cornerRadius = radius
    // Always mask the inside view
    self.contentView.layer.masksToBounds = true
    
    self.layer.shadowColor = UIColor.black.cgColor
    self.layer.shadowOffset = CGSize(width: 0, height: 1.0)
    self.layer.shadowRadius = 3.0
    self.layer.shadowOpacity = 0.5
    // Never mask the shadow as it falls outside the view
    self.layer.masksToBounds = false
    
    // Matching the contentView radius here will keep the shadow
    // in sync with the contentView's rounded shape
    self.layer.cornerRadius = radius
    

    Now when ever the cells size change the view API will do all the work internally.

提交回复
热议问题