swift - 以编程方式自定义单元格和堆栈视图
问题描述
我正在以编程方式创建一个带有自定义单元格的表格视图。我想在自定义单元格中使用带有排列子视图的堆栈视图。然而,我所有的努力都失败了。首先可以做到这一点吗?
其次,我将代码放在:
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: "cellId")
我正在使用此代码创建堆栈视图:
let thestack: UIStackView = {
let sv = UIStackView()
sv.distribution = .fillEqually
sv.axis = .vertical
sv.spacing = 8
return sv
}()
但是我不能将排列好的子视图添加到此之外,在我 addsubview(thestack) 并列出所有约束之后 - 我的数据都没有显示在自定义单元格中。任何帮助,将不胜感激。
解决方案
对的,这是可能的。如下所示:
class CustomTableViewCell: UITableViewCell {
let stackView: UIStackView = {
let stackView = UIStackView()
stackView.translatesAutoresizingMaskIntoConstraints = false
stackView.spacing = 10
stackView.distribution = .fillEqually
return stackView
}()
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: .default, reuseIdentifier: reuseIdentifier)
addSubview(stackView)
stackView.leftAnchor.constraint(equalTo: leftAnchor, constant: 10).isActive = true
stackView.topAnchor.constraint(equalTo: topAnchor, constant: 10).isActive = true
stackView.rightAnchor.constraint(equalTo: rightAnchor, constant: -10).isActive = true
stackView.bottomAnchor.constraint(equalTo: bottomAnchor, constant: -10).isActive = true
let redView = UIView()
redView.backgroundColor = .red
let yellowView = UIView()
yellowView.backgroundColor = .yellow
let blackView = UIView()
blackView.backgroundColor = .black
stackView.addArrangedSubview(redView)
stackView.addArrangedSubview(yellowView)
stackView.addArrangedSubview(blackView)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
推荐阅读
- java - 如何从另一个类访问片段类中呈现的 TextView 和进度条
- javascript - 如何防止在java脚本上重新刷新页面?
- go - 包的 `init()` 函数中的无限循环 - 好主意还是坏主意?
- ios - Fastlane 扫描在当前测试会话未完成时启动新的测试会话
- java - 我可以在多个地方使用相同的片段吗?
- mysql - 是什么降低了这个产品搜索 MySQL 查询的速度?
- spotfire - 如何使用 C# API 删除 FilteringScheme?
- r - 基于匹配字符的折叠因子级别
- vb.net - 如何使用功能来防止datagridview的重复记录
- angular - 如何将动态创建的输入元素绑定到 FormGroup?