在下面的代码中,我使用didSet
更新自定义TableViewCell标签和图像的值。
我最初尝试更改init
的{{1}}方法。我尝试将其更改为:
ArtistTableViewCell
但那不起作用,因为它似乎是这条线:
init(style: UITableViewCellStyle, reuseIdentifier: String?, artist: Artist) {
self.artist = artist
...
}
想要只使用此签名调用方法:
let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) as! ArtistTableViewCell
所以我目前的代码是有效的。但它没有init(style: UITableViewCellStyle, reuseIdentifier: String?)
作为初始化的属性,如下所示:
artist
这就是我所说的:
import UIKit
class ArtistTableViewCell: UITableViewCell {
var artist: Artist!{
didSet{
bioLabel.text = artist.bio
nameLabel.text = artist.name
artistImageView.image = artist.image
}
}
lazy var bioLabel : UILabel = {
let label = UILabel()
label.translatesAutoresizingMaskIntoConstraints = false
label.numberOfLines = 0
return label
}()
lazy var nameLabel : UILabel = {
let label = UILabel()
label.backgroundColor = .cyan
label.translatesAutoresizingMaskIntoConstraints = false
return label
}()
lazy var artistImageView : UIImageView = {
let imageView = UIImageView()
imageView.translatesAutoresizingMaskIntoConstraints = false
return imageView
}()
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
contentView.addSubview(bioLabel)
contentView.addSubview(nameLabel)
contentView.addSubview(artistImageView)
NSLayoutConstraint.activate([
bioLabel.leadingAnchor.constraint(equalTo: contentView.centerXAnchor, constant: 8),
bioLabel.topAnchor.constraint(equalTo: contentView.topAnchor),
bioLabel.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -8),
bioLabel.bottomAnchor.constraint(equalTo: contentView.bottomAnchor)
])
NSLayoutConstraint.activate([
artistImageView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor,constant: 8),
artistImageView.topAnchor.constraint(equalTo: contentView.topAnchor),
artistImageView.trailingAnchor.constraint(equalTo: contentView.centerXAnchor, constant: -8),
artistImageView.bottomAnchor.constraint(equalTo: nameLabel.topAnchor, constant: -8)
])
NSLayoutConstraint.activate([
nameLabel.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 8),
nameLabel.trailingAnchor.constraint(equalTo:contentView.centerXAnchor, constant: -8),
nameLabel.bottomAnchor.constraint(equalTo: contentView.bottomAnchor)
])
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}