简体   繁体   中英

Connecting Outlet to Constraint in Custom View Instantiated from xib File Results in Crash

I have a custom UIView subclass, whose layout is defined in a .xib file.

I create instaces with a class method that loads the xib from the app's bundle, like this:

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
    }
}

This code works as expected. I use this view as a custom navigation title in a view controller.

The xib has autolayout constraints to:

  • Center the label horizontally and vertically in its superview,
  • Center the button vertically with respect to the label,
  • Fix the horizontal space between the label and the button.

Next, I wish to put a width constraint to the label, and connect it to an outlet in the above code so that I can control it at runtime (to deal with truncation of text too long, etc.).

The xib's File Owner is set to my custom class. I connect a "New Referencing Outlet" from the width constraint to a new outlet in my class:

@IBOutlet weak var widthConstraint:NSAutolayoutConstraint!

When I run my code, it crashes at this line:

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

with the error:

This class is not key value coding-compliant for the key widthConstraint

What am I missing?


Note: None of the following helped

  • Clean build folder and rebuild.
  • Disconnect outlet and reconnect.
  • Connect outlet to another (existing) constraint.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM