swift - UITableviewCell : set constraints programmatically inside ContentView using autoresize

标签 swift uitableview constraints

我试图限制 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
}

但这不是您需要在 cellForRowAtdequeueResuableCell 生成单元格而不是创建变量的正确方法

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/

相关文章:

swift - 无法调用非函数类型的值 'CGFloat'

swift - UICollectionViewCell 未正确重用

ios - 表格中的第一个单元格始终为空。仅从第二个单元格显示 - objective-c

iphone - Xcode:使用 NSUserDefaults 和 TableView 保存数据问题

ios - 仅在 UITableView 中循环遍历 textFields

iOS UITableView 在设置 TableHeaderView 后以编程方式覆盖自动布局约束

json - Firebase 不断更改 JSON 文件

python - 安装 coremltools 时出错

templates - 检查类型是否是模板的实例化

sql-server - 重用检查约束