【问题标题】:Connecting Outlet to Constraint in Custom View Instantiated from xib File Results in Crash在从 xib 文件实例化的自定义视图中将插座连接到约束导致崩溃
【发布时间】:2016-06-03 17:22:13
【问题描述】:

我有一个自定义 UIView 子类,其布局在 .xib 文件中定义。

我使用从应用程序包中加载 xib 的类方法创建实例,如下所示:

class CustomTitleView: UIView
{
    @IBOutlet weak var titleLabel: UILabel!

    @IBOutlet weak var infoButton: UIButton!

    class func instance() -> CustomTitleView
    {
        return UINib(nibName: "CustomTitleView", bundle: nil).instantiateWithOwner(self, options: nil)[0] as! CustomTitleView
    }
}

此代码按预期工作。我将此视图用作视图控制器中的自定义导航标题。

xib 具有自动布局约束:

  • 标签在其父视图中水平和垂直居中,
  • 按钮相对于标签垂直居中,
  • 修复标签和按钮之间的水平间距。

接下来,我希望给标签添加一个width 约束,并将其连接到上述代码中的一个插座,以便我可以在运行时控制它(处理文本截断过长等问题)。

xib 的文件所有者设置为我的自定义类。 我将宽度约束中的“新参考插座”连接到班级中的新插座:

@IBOutlet weak var widthConstraint:NSAutolayoutConstraint!

当我运行我的代码时,它在这一行崩溃:

return UINib(nibName: "CustomTitleView", bundle: nil).instantiateWithOwner(self, options: nil)[0] as! CustomTitleView

出现错误:

这个类不符合键宽度约束的键值编码

我错过了什么?


注意:以下都没有帮助

  • 清理构建文件夹并重新构建。
  • 断开插座并重新连接。
  • 将插座连接到另一个(现有)约束。

【问题讨论】:

    标签: ios swift autolayout interface-builder xib


    【解决方案1】:

    我看到的唯一奇怪的事情是使用 NSAutoLayoutConstraint 而不是 NSLayoutConstraint

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-24
      • 2023-03-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多