如何正确编写约束代码

史考特

我想在里面设置一个UITextView UITableViewCell在TableView函数的某些方法中,我编写了以下代码,但是它导致以下错误:

由于未捕获的异常“ NSGenericException”而终止应用程序,原因:“无法激活具有锚点的约束,并且它们没有共同的祖先。约束或其锚点是否引用了不同视图层次结构中的项目?那是非法的。

这是我在tableView中的代码:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = newTableView.dequeueReusableCell(withIdentifier: "NewCell", for: indexPath) as! NewCellTableViewCell
    let tableTextView = UITextView()
    tableTextView.translatesAutoresizingMaskIntoConstraints = false
    tableTextView.leadingAnchor.constraint(equalTo: cell.leadingAnchor).isActive = true
    tableTextView.topAnchor.constraint(equalTo: cell.topAnchor).isActive = true
    tableTextView.widthAnchor.constraint(equalTo: cell.widthAnchor).isActive = true
    tableTextView.heightAnchor.constraint(equalTo: cell.heightAnchor).isActive = true
    cell.addSubview(tableTextView)
    return cell
}
安德里亚·穆尼亚尼(Andrea Mugnaini)

首先,您应该致电:

cell.addSubview(tableTextView)

然后附加约束,此外:

所有约束都必须仅涉及接收视图范围内的视图。具体来说,涉及的任何视图都必须是接收视图本身,或者是接收视图的子视图。

因此,您的代码可能是:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = newTableView.dequeueReusableCell(withIdentifier: "NewCell", for: indexPath) as! NewCellTableViewCell
    let tableTextView = UITextView()
    cell.addSubView(tableTextView)
    tableTextView.translatesAutoresizingMaskIntoConstraints = false

    tableTextView.leadingAnchor.constraint(equalTo: cell.leadingAnchor).isActive = true
    tableTextView.topAnchor.constraint(equalTo: cell.topAnchor).isActive = true
    tableTextView.widthAnchor.constraint(equalTo: cell.widthAnchor).isActive = true
    tableTextView.heightAnchor.constraint(equalTo: cell.heightAnchor).isActive = true
    return cell
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

如何正确编写构造函数

如何编写能够正确地要求最低版本的python版本的Python代码?

如何编写dockerfile从我的github正确提取代码

编写代码错误以获取正确的数学结果

当空指针不全为零时如何正确编写C / C ++代码

如何正确编写成功的插件代码?

如何编写成功的Jquery检查,验证和重定向的正确代码

如何防止编写相同的代码?无法正确编写装饰器。蟒蛇

如何在pg-promise中正确编写具有空约束的查询?

如何正确声明约束

如何编写以下代码的类型约束

如何编写可正确缩进方案代码的JavaScript函数?

PuLP:如何编写多变量约束?

如何编写SASS代码?

如何正确编写异步方法?

如何以正确的方式编写以下代码以打印返回值

编写Ruby代码的正确方法是什么?

如何正确编写通过onClick事件更改div文本的JavaScript代码

如何正确设置约束?

无法为Java模式编写正确的代码

如何编写SDC时序约束加密的Verilog代码?

如何正确编写在登录后显示用户名的 PHP 代码?

尝试调整文本输入的大小。(Kivy、QPython、Android)。但不确定如何正确编写代码

如何正确编写对多个索引的约束?

如何在 html 表单操作中正确编写此 php 代码?

如何在 Kotlin 中正确编写此正则表达式以测试 Pascal 中的代码

如何正确编写@POST 请求?

如何在excel中正确编写此vba代码

如何编写继承类,因为我不明白如何正确编写代码