ios - 无法为 TableView 的自定义单元格设置任何属性。此外,当我在 cellsForRowAt 函数中填充表时,它返回空表
问题描述
无法将属性设置为表格视图的自定义单元格。此外,无法在 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
}
}
我还想为这个新的自定义单元格添加约束。
解决方案
尝试使用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 ...
)]
推荐阅读
- css - 如何在键盘可访问性焦点上关闭汉堡菜单
- r - prcomp R 基函数中的主动变量和补充变量
- python - 给定像素 (x,y) 位置返回 (row, column) 元组
- php - 如何使用 PHP 更新现有的数组数组?
- javascript - Javascript 生成器不会产生新的结果
- c# - 天蓝色函数时间触发器和天蓝色sql数据库与c#之间的连接:错误。如何修复它
- scala - 如何将查询写入 es.query
- html - 如何通过 pathVariable 在 url 中使用我的 HTML 表单的字段?
- java - Android自定义视图onDraw方法在第二次启动活动无效后未调用
- swift - swift MaterialComponents.MDCTabBarView mdc_customView 无法正常工作