soleil
soleil

Reputation: 13135

Subclassing UIView in Swift - error

I have a file called MyView.swift that just looks like this:

class MyView : UIView {

}

I also have a MyView.xib file with a view with class set to MyView.

In a view controller I have this:

var myView: MyView?

override func viewDidLoad() {
    super.viewDidLoad()

    self.myView = NSBundle.mainBundle().loadNibNamed("MyView", owner: nil, options: nil)[0] as MyView
    self.myView.frame = frame;
    self.view.addSubview(self.myView);

}

I get this error:

MyView? does not have a member named 'frame'

Why? MyView is a subclass of UIView...

Upvotes: 3

Views: 2265

Answers (2)

Brian Tracy
Brian Tracy

Reputation: 6831

You will have to implicit unwrap that optional, or use optional chaining.

self.myView!.frame = frame

Or utilize optional chaining.

self.myView?.frame = frame 
// can do this now in Swift.

The first option is more dangerous because when you forcefully unwrap an optional, and it is nil, a runtime error will occur.

Edit I apologize, optional chaining is not the right tool for the job here. It is the right tool if you wanted to query the value of the frame. Alternatively, you could use the if let syntax.

if let optionalView = self.myView {
    var queriedFrame = optionalView.frame
}

Upvotes: 4

fqdn
fqdn

Reputation: 2843

MyView is a subclass of UIView, but MyView? is an Optional which has only two possible cases:

(1) it is nil, or

(2) it holds a wrapped value of type MyView

...and in either case, it is still an Optional, which means it doesn't have a member named 'frame' :) though if it's holding a wrapped value of MyView then that wrapped value does!

To get at that wrapped value (assuming it has one) it is necessary for you to either explicitly unwrap it with ! or for you to use Optional Binding (if let) in accessing its properties.

Upvotes: 3

Related Questions