I'm trying to create a custom UIView (CardView
) and display it in a UITableView
class CardView: UIView {
public var cardTitle = UILabel()
public var cardValue = UILabel()
override init(frame: CGRect) {
super.init(frame: frame)
backgroundColor = .secondarySystemBackground
self.addSubview(cardTitle)
self.addSubview(cardValue)
layer.cornerRadius = 10
cardTitle.frame = CGRect(x: 0, y: 10, width: self.width, height: 25)
cardValue.frame = CGRect(x: 0, y: cardTitle.bottom + 1, width: self.width, height: 25)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
The TableView looks like this:
class StatsTableViewCell: UITableViewCell {
static let identifier = "StatsID"
private var cellTitleLabel: UILabel = {
let label = UILabel()
return label
}()
private var homeView: CardView = {
let card = CardView()
card.cardTitle.text = "Home"
return card
}()
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
addSubview()
}
override func layoutSubviews() {
super.layoutSubviews()
cellTitleLabel.frame = CGRect(x: 10, y: 10, width: contentView.width - 20, height: 20)
homeView.frame = CGRect(x: 10, y: cellTitleLabel.bottom + 10, width: (contentView.width - 40) / 3, height: contentView.height - 25)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func addSubview() {
contentView.addSubview(cellTitleLabel)
contentView.addSubview(homeView)
}
func configure(with viewModel: StatsTableviewViewModel) {
cellTitleLabel.text = viewModel.cellTitle
homeView.cardValue.text = viewModel.homeValue
}
}
On my cellForRowAt
im tryin to configuring the cell like this:
extension WelcomeViewController: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
viewmodels.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(withIdentifier: StatsTableViewCell.identifier, for: indexPath) as? StatsTableViewCell else {
fatalError()
}
print(viewmodels)
cell.configure(with: viewmodels[indexPath.row])
return cell
}
}
The problem is that in the StatsViewController
it shows the homeView
background and the cellTitleLabel
but is not showing the cardTitle
and cardValue
Screenshot of the StatsTableView
I'm using an extension to access easier to width and height. That's why you're not seeing .frame.size.height
cardTitle
andcardValue
asself.width
during the initialisation ofCardView
, which at that point of time is 0 as you only assign the frame of yourCardView
after.