我试图限制 TableViewCell 中的元素(UIView 或 UITextfield)。如果我使用像
这样的框架
UITextField(frame: CGRect(x: 150, y: 0, width: 500, height: 110))
一切正常。
但是我正在尝试使用 autoresize 并且不知何故我的 UITextfield 在我的 Cell 中添加为 SubView 没有相同的祖先。错误消息是:
“它们没有共同的祖先。约束或其 anchor 是否引用了不同 View 层次结构中的项目?”
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var Testtext: UITextField{
let test = UITextField(frame: CGRect(x: 150, y: 0, width: 500, height: 110))
test.textColor = .red
test.font = .boldSystemFont(ofSize: 22)
test.text = "Hello World"
return test
}
var cell:UITableViewCell {
let createdCell = UITableViewCell()
createdCell.contentView.addSubview(Testtext)
// Testtext.translatesAutoresizingMaskIntoConstraints = false
// NSLayoutConstraint.activate([
// Testtext.topAnchor.constraint(equalTo: createdCell.topAnchor),
// Testtext.bottomAnchor.constraint(equalTo: createdCell.bottomAnchor),
// Testtext.trailingAnchor.constraint(equalTo: createdCell.trailingAnchor),
// Testtext.leadingAnchor.constraint(equalTo: createdCell.leadingAnchor)
// ])
return createdCell
}
顺便说一句:我不想创建 Cellclass,因为我需要根据输入数组数调整文本字段和 UIView 的数量。
最佳答案
你需要
var cell:UITableViewCell {
let createdCell = UITableViewCell()
createdCell.contentView.addSubview(Testtext)
Testtext.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
Testtext.topAnchor.constraint(equalTo: createdCell.contentView.topAnchor),
Testtext.bottomAnchor.constraint(equalTo: createdCell.contentView.bottomAnchor),
Testtext.trailingAnchor.constraint(equalTo: createdCell.contentView.trailingAnchor),
Testtext.leadingAnchor.constraint(equalTo: createdCell.contentView.leadingAnchor)
])
return createdCell
}
但这不是您需要在 cellForRowAt
中 dequeueResuableCell
生成单元格而不是创建变量的正确方法
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! CustomCell
return cell
}
关于swift - UITableviewCell : set constraints programmatically inside ContentView using autoresize,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58525658/