I created a UITableViewCell that is basically a card with a shadow behind it. I want to make this the base class used for all other custom UITableView Controllers. However, when I used the code below, the Shadowed Card doesn’t show up. Why is this?
ShadowCardTableViewCell
class ShadowCardTableViewCell: UITableViewCell {
let borderView = UIView(frame: .zero)
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
changeToShadowedCard()
self.contentView.layoutIfNeeded()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
func changeToShadowedCard() {
backgroundColor = .clear
contentView.addSubview(borderView)
borderView.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
borderView.topAnchor.constraint(equalTo: self.contentView.topAnchor, constant: 10),
borderView.bottomAnchor.constraint(equalTo: self.contentView.bottomAnchor, constant: -10),
borderView.rightAnchor.constraint(equalTo: self.contentView.rightAnchor, constant: -10),
borderView.leftAnchor.constraint(equalTo: self.contentView.leftAnchor, constant: 10),
])
borderView.backgroundColor = .secondarySystemBackground
borderView.layer.cornerRadius = 7.5
borderView.addShadow(shadowColor: UIColor.label.cgColor, shadowOffset: CGSize(width: 0, height: 0), shadowOpacity: 0.3, shadowRadius: 4)
}
}
OtherTableViewCell
class OtherTableViewCell: ShadowCardTableViewCell {
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
}
2
Answers
Firstly, you cannot make UITableViewCell a base class for a UiViewController.
What you can do is provide an extension for you UITableViewCell, something along these lines:
and after registering a cell and initializing it, call it like:
You haven’t shown what your
borderView.addShadow(...)
func is doing, but this is working fine for me:Result: