【发布时间】:2018-10-13 11:10:10
【问题描述】:
我正在尝试在 Swift Playground 中尝试约束,然后发疯了。我有一个小的class CLListTableViewCell: UITableViewCell,里面有一个UILabel:
let nameLabel: UILabel = {
let label = UILabel()
label.text = "Here is a great text"
label.translatesAutoresizingMaskIntoConstraints = false
label.textAlignment = .left // text alignment in center
return label
}()
我有一个设置布局的函数,我在 init 结束时调用它:
func addSubViewsAndLayout() {
contentView.addSubview(nameLabel)
let views = ["nameLabel": nameLabel]
let horizontalConstraintsStringRepresentation = "H:|-[nameLabel]-|"
let horizontalConstraints = NSLayoutConstraint.constraints(withVisualFormat: horizontalConstraintsStringRepresentation, options: .alignAllCenterY, metrics: nil, views: views)
let verticalConstraintsStringRepresentation = "V:|-[nameLabel]-|"
let verticalNameConstraints = NSLayoutConstraint.constraints(withVisualFormat: verticalConstraintsStringRepresentation, options: .alignAllLeading, metrics: nil, views: views)
NSLayoutConstraint.activate(horizontalConstraints)
NSLayoutConstraint.activate(verticalNameConstraints)
}
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
addSubViewsAndLayout()
}
我得到的只是一个漂亮的、白色的、空的牢房。 任何人都可以指出我在这里做错了什么?任何缺少的约束? Playground 控制台中没有任何指示。
--- 编辑 ---
问题似乎来自我在其中显示单元格的 tableView。代码如下:
class TableViewController : UITableViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 2
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as? CLListTableViewCell ?? CLListTableViewCell(style: .default, reuseIdentifier: "cell")
return cell
}
override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return "Section \(section)"
}
}
--- 编辑 2 ---
【问题讨论】:
-
尝试将标签的文本颜色和背景颜色设置为不同的值,并验证它是否正常工作。因为我在操场上尝试了相同的代码并且它正在工作。
-
不,将
label.backgroundColor = UIColor.clear和label.textColor = UIColor.black添加到 nameLabel 定义不会改变任何内容。但是,问题可能来自 tableView。如果我直接在操场上显示单元格,它就可以工作。如果在 tableview 中,它保持空白。 -
你能提供你的游乐场的截图和输出吗?
-
补充:TableViewController的截图和代码。
标签: ios swift uitableview nslayoutconstraint swift-playground