NSWindow.contentLayoutGuide type Any?

In the 2016 WWDC session "Crafting Modern Cocoa Apps", there is a description of how to set the offset of a window's content when using the "Full Size Content View" setting:


override func updateViewConstraints() {
  if topConstraint == nil {
    if let topAnchor = titleTextField.window?.contentLayoutGuide?.topAnchor {
      topConstraint = titleTextField.topAnchor.constraint(equalTo: topAnchor, constant: 2)
      topConstraint!.isActive = true
    }
  }
  super.updateViewConstraints()
}



However, in Xcode 8.1 [editted], this does not compile, because NSWindow's contentLayoutGuide property is declared as

    open var contentLayoutGuide: Any? { get }


Has anyone successfully used this property? If so, how? Did you have to cast the Any? type to something concrete, and if so, what?

Replies

Am I really the first one to try this under Xcode 8.1 [edited]?

Argh... I just realized I typed Xcode 7.1... That's wrong—Sorry, just habbit. No wonder nobody replied, LOL


This is happening in 8.1, and now 8.2.

contentLayoutGuide is internally of type NSLayoutGuide.

So all you have to do is cast it to NSLayoutGuide
Code Block
if let guide = titleTextField.window?.contentLayoutGuide as? NSLayoutGuide {
let topAnchor = guide.topAnchor
}



@kaunteya that is not correct. Internally it may be either a NSLayoutGuide or an NSView. The Any? "hack" is necessary since there is no protocol to express *anchor properties. But in practice it will be an NSLayoutGuide most of the time unless you customize window's content view or play with its view hierarchy.