Невозможно установить свойства пользовательской ячейки для табличного представления. Кроме того, невозможно присвоить значение пользовательской ячейке в функции cellForRowAt. Я использую Swift 5 и Xcode 10.2.
import UIKit
class ContainerViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
let CellId = "CellId"
let tableView : UITableView = {
let tv = UITableView()
tv.allowsSelection = false
tv.separatorStyle = .none
return tv
}()
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: CellId, for: indexPath) as! Cell
//cell.labelView.textColor = .red -- tried to set color here
cell.labelView.text = "Label \(indexPath.row)" // this code doesn't seems to work
return cell
}
}
//- Custom Cell Class
class Cell: UITableViewCell{
let cellView : UIView = {
let view = UIView()
view.backgroundColor = UIColor.red // -- this property doesn't reflect. Also, i want to add shadow to this view any suggestions?
return view
}()
let labelView: UILabel = {
let label = UILabel()
label.textColor = UIColor.black // -- this property doesn't reflect
label.font = UIFont.boldSystemFont(ofSize: 16) // -- this property doesn't reflect
return label
}()
func setUpCell() {
//-- Also tried to set properties here but no luck
//backgroundColor = UIColor.yellow
//labelView.textColor = UIColor.black
addSubview(cellView)
cellView.addSubview(labelView)
//cellView.backgroundColor = .green
}
}
Я также хочу добавить ограничение в эту новую пользовательскую ячейку.
да, я назначил tableView.delegate = self и tabbleView.dataSource = self. Кроме того, я зарегистрировал класс Custom Cell в tableView.
попробуйте использовать contentView.addSubview(cellView)
вместо addSubview(celliIew)
Поскольку вы хотите использовать ограничения автомакета, убедитесь, что вы установили cellView. translatesAutoResizingMaskIntoConstraints = false
(То же самое для просмотра этикетки)
и тогда вы можете начать
NSLayoutConstraints.activate([
cellView.topAnchor.constraint(equalTo: contentView.topAnchor),
cellView.bottomAnchor.constraint(equalTo: contentView.bottomAnchor),
cellView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor),
cellView.trailingAnchor.constraint(equalTo: contentView.trailingAnchor),
... Setup label constraints ...
)]
Вы назначили делегата и источник данных tableView для viewController?