Adding View controllers as subview in Swift

故事扮演 提交于 2020-01-04 19:50:00

问题


Am trying to build a simple calculator app using swift. I have created two view controller with the basic and advanced options. Earlier in Obj-C used to do this

[[AViewController alloc] initWithNibName:@"nibName" bundle:nil]

In swift I cannot even import my new view controllers. But still I can declare as var aViewController:AViewController? and use it. But I am stuck at loading nib

I tried with AViewController(nibName: "nibname", bundle: nil), but everything results in compiler error Could not find an overload for __conversion that accepts the supplied arguments


回答1:


Try this one,

AViewController(nibName: "nibname", bundle: NSBundle.mainBundle())

This works perfect for me.

Declaration : SWIFT (UINib Class Reference)

init(nibName name: String!,
      bundle bundleOrNil: NSBundle!) -> UINib

Declaration : SWIFT (UIViewController Class Reference)

init(nibName nibName: String!,
      bundle nibBundle: NSBundle!)

The exclamation mark effectively says, “I know that this optional definitely has a value; please use it.” This is known as forced unwrapping of the optional’s value.

This is the reason, we cannot pass "nil" as second parameter i.e bundle

Cheers..!




回答2:


Looks like nil was the one causing trouble when I replaced it with NSBundle.mainBundle() it worked.



来源:https://stackoverflow.com/questions/24257695/adding-view-controllers-as-subview-in-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!