ios - Swift 中视觉约束的奇怪问题,因为相关 View 没有 super View

标签 ios swift constraints

我正在尝试将 UITableView 创建为:

var myTableView: UITableView {
    let tableView = UITableView()

    tableView.translatesAutoresizingMaskIntoConstraints = false
    tableView.backgroundColor = .brown

    tableView.delegate = self
    tableView.dataSource = self

    return tableView
}

然后在viewDidLoad内部添加视觉约束,如下:

view.addSubview(myTableView)

var c = [NSLayoutConstraint]()
c += NSLayoutConstraint.constraints(withVisualFormat: "H:|-[v0]-|", options: .alignAllCenterX, metrics: nil, views: ["v0": myTableView])
NSLayoutConstraint.activate(c)

但我在运行时收到错误:

Unable to parse constraint format: 
Unable to interpret '|' character, because the related view doesn't have a superview 
H:|-[v0]-| 

我不明白为什么会发生这种情况,因为我在 addSubview 之后添加了约束,所以它应该找到 super View ,但它不能。 有人可以帮我解释一下这个问题吗?

最佳答案

这应该有效

  var myTableView: UITableView  = UITableView ()

 override func viewDidLoad() {
        super.viewDidLoad()
        myTableView.translatesAutoresizingMaskIntoConstraints = false
        myTableView.backgroundColor = .brown

        myTableView.delegate = self
        myTableView.dataSource = self
        self.view.addSubview(myTableView)
        constraintsWithFormat(format: "H:|[v0]|", views: myTableView)
        constraintsWithFormat(format:"V:|[v0]|" , views: myTableView)

        // Do any additional setup after loading the view.
    }


     func constraintsWithFormat(format:String , views:UIView...)
    {
        var viewsDic = [String: UIView]()
        for (index , view ) in views.enumerated() {
            let key = "v\(index)"

            viewsDic[key] = view
            view.translatesAutoresizingMaskIntoConstraints = false
        }

        let constraints =   NSLayoutConstraint.constraints(withVisualFormat: format, options: [], metrics: nil, views: viewsDic)
        NSLayoutConstraint.activate(constraints)





    }

关于ios - Swift 中视觉约束的奇怪问题,因为相关 View 没有 super View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50352108/

相关文章:

ios - 如果我们在真正的预提交处理程序中,由于 CA 限制,我们实际上不能添加任何新的栅栏

ios - iPad 用户界面设计选项

ios - 将 BGRA 转换为 ARGB

ios - 如何从 NSString 中捕获最后 4 个字符

ios - 调用 KeyboardDidHide 时无法更改 UIView 高度

sql - 在主键冲突错误后继续事务

forms - Symfony 检查表单验证时两个字段中是否至少有一个不为空

ios - 寻找Xcode构建脚本以在目标之间复制文件

ios - touchesBegan 不触发

ios - 调整 UIImage 大小时内存泄漏