Home > Software engineering >  Dropping shadow inside UITableView Cell doesn't work in Swift
Dropping shadow inside UITableView Cell doesn't work in Swift

Time:04-25

My project doesn't use Storyboards since it's using CleanSwift architecture. Every views are built programmatically. Here's my table cell class.

class LiveScoreCell: UITableViewCell {

var data: LiveScores.Data? {
    didSet {
        leagueLogo.setImage(data?.leagueLogo)
    }
}

var container: UIView = {
    let view = UIView()
    view.backgroundColor = .white
    view.layer.cornerRadius = 10
    view.layer.shadowColor = UIColor.black.cgColor
    view.layer.shadowOffset = .zero
    view.layer.shadowOpacity = 0.6
    view.layer.shadowRadius = 10
    view.layer.shadowPath = UIBezierPath(rect: view.bounds).cgPath
    view.layer.borderWidth = 1
    view.translatesAutoresizingMaskIntoConstraints = false
    return view
}()
    
var leagueLogo: UIImageView = {
    let imgView = UIImageView()
    imgView.translatesAutoresizingMaskIntoConstraints = false
    return imgView
}()

override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
    super.init(style: style, reuseIdentifier: reuseIdentifier)
    selectionStyle = .none
    setupViews()
}

required init?(coder: NSCoder) {
    super.init(coder: coder)
    selectionStyle = .none
    setupViews()
}

override func prepareForReuse() {
    super.prepareForReuse()
}


func setupViews() {
    addSubview(container)
    container.topAnchor.constraint(equalTo: self.topAnchor, constant: 8).isActive = true
    container.bottomAnchor.constraint(equalTo: self.bottomAnchor, constant: -8).isActive = true
    container.leadingAnchor.constraint(equalTo: self.leadingAnchor, constant: 8).isActive = true
    container.trailingAnchor.constraint(equalTo: self.trailingAnchor, constant: -8).isActive = true
    
    addSubview(leagueLogo)
    leagueLogo.topAnchor.constraint(equalTo: container.topAnchor, constant: 8).isActive = true
    leagueLogo.leadingAnchor.constraint(equalTo: container.leadingAnchor, constant: 8).isActive = true
    leagueLogo.widthAnchor.constraint(equalToConstant: 26).isActive = true
    leagueLogo.heightAnchor.constraint(equalToConstant: 26).isActive = true
}
    
}

And the result is .. enter image description here

Only border involves.. Any idea why is this happening?

CodePudding user response:

As of this line

view.layer.shadowPath = UIBezierPath(rect: view.bounds).cgPath

runs when bounds is zero so make it inside

override func layoutSubviews() {
  super.layoutSubviews()
  container.layer.shadowPath = UIBezierPath(rect: container.bounds).cgPath
}
  • Related