iOS 在 Swift 中以编程方式添加约束

标签 ios swift nslayoutconstraint

所以,我已经在 Xcode 中使用了 IB,并且想在 Swift 中编写所有 UI

所以我所做的是:

  • 创建了一个新的 UIView 以包含我要编写的元素 - 我们称它为“TestView”
  • 我已将 TestView 作为 subview 添加到 VC
  • TestView 类中,我添加了如下元素:

    class TestView: UIView {
          var someLabel:UILabel!
          override init(frame: CGRect) {
                super.init(frame: frame)
    
                self.someLabel = UILabel(frame: CGRect(x: self.frame.midX, y: oneSixthHeight, width: 100, height: 22))
                self.someLabel.text = "test"
    
                var constraints:[NSLayoutConstraint] = []
                self.someLabel.translatesAutoresizingMaskIntoConstraints = false
                let rightsideAnchor:NSLayoutConstraint = NSLayoutConstraint(item: self.someLabel, attribute: .Trailing, relatedBy: .Equal, toItem: self, attribute: .Trailing, multiplier: 1, constant: 1)
    
                 constraints.append(rightsideAnchor)
                 NSLayoutConstraint.activateConstraints(constraints)
          }
    }
    

有了这个,我希望 UILabel 锚定到 View 的右侧。

但是,我确实遇到了这个错误:

Terminating app due to uncaught exception 'NSGenericException', reason: 'Unable to activate constraint with items > and > because they have no common ancestor.
Does the constraint reference items in different view hierarchies? That's illegal.'

我做错了什么?

最佳答案

只有在将 View 添加到 View 层次结构后才应添加约束。从您的代码中可以清楚地看出您没有添加要查看的 UILabel 实例。

关于iOS 在 Swift 中以编程方式添加约束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40839981/

相关文章:

android - 移动应用——在后端存储和版本化相对静态的json文件

ios - 将谷歌分析集成到 iOS 应用程序中

ios - AVPlayerStatusFailed 和错误代码 "Cannot Decode"

ios - UISegmentedControl 作为 UINavigationBar 标题项在一些延迟后加载

ios - 角标(Badge) View 如何使用全自动布局方法创建

子类中的 Swift 约束

javascript - 我可以使用 sendBeacon 在 iOS 设备中实时保存 session 持续时间指标吗?

ios - 在 DetailViewController 中的索引路径之间转换? swift

ios - swift - 如何完成任务

ios - LayoutConstraints - 无法同时满足约束