简体   繁体   中英

Loading a Swift based UIViewController from Objective-C

I am attempting to load a view controller nib whose File's Owner is a Swift based UIViewController class. The view controller is very simple at this point--just a single label ( lblResult ) whose contents get set at runtime. When loading the view controller, I get the following error:

this class is not key value coding-compliant for the key lblResult

I know that this is usually because the File's Owner is not set in Interface Builder, however, in my case it IS set. I have verified that the IBOUtlet for lblResult is properly set and that the view property is also properly set. The only real difference here is that I am attempting to load the swift based view controller within an app written in Objective-C.

In my view controller class I am setting the UILabel property as follows:

@IBOutlet weak var lblResult: UILabel!

and setting its value as follows:

lblResult.text = "Time \(hour):\(minute):\(second)"

In my Obj-C calling class, I am instantiating the view controller as follows:

viewController = [[UIViewController alloc] initWithNibName:@"SwfViewController" bundle:nil];

The nib loads into view when no outlets are set, but when there are IBOutlets, i get the error. Any clues as to why this is happening? Thanks!

Is this view controller present in your storyboard? If yes, you need to load the view controller by calling.

viewController = self.storyboard?.instantiateViewControllerWithIdentifier("SwfViewController") as SwfViewController

Make sure you set the identifier of the view controller in the storyboard to SwfViewController.

The storyboard should look something like this.

在此处输入图片说明

If your nib is a View and the owner is a View Controller, make sure you connect your view controller's view property to the nib view. If your nib is a view controller, instead of setting the File Owner just set the Custom Class of the view controller to SwfViewController.

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