我知道这方面已经存在一些问题,但我无法弄明白。之前解决的问题将表明' profileViewController'是零,但我不知道为什么会这样。用户界面完全是程序化的,没有IB。获得:
"致命错误:无法打开Optional.None"
在pushViewController()中的代码如下:
class FavoritesViewController: UIViewController {
init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
// Custom initialization
self.title = "Favorites"
self.tabBarItem.image = UIImage(named: "MikeIcon")
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
self.view.backgroundColor = UIColor.redColor()
let profileButton = UIButton.buttonWithType(.System) as UIButton
profileButton.frame = CGRectMake(60, 300, 200, 44)
profileButton.setTitle("View Profile", forState: UIControlState.Normal)
profileButton.addTarget(self, action: "showProfile:", forControlEvents: UIControlEvents.TouchUpInside)
self.view.addSubview(profileButton)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func showProfile(sender: UIButton) {
let profileViewController = ProfileViewController(nibName: nil, bundle: nil)
self.navigationController.pushViewController(profileViewController, animated: true)
}
这里是 AppDelegate.swift 的相关部分:
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: NSDictionary?) -> Bool {
self.window = UIWindow(frame: UIScreen.mainScreen().bounds)
// Override point for customization after application launch.
let feedViewController = FeedViewController(nibName: nil, bundle: nil)
let favoritesViewController = FavoritesViewController(nibName: nil, bundle: nil)
let profileViewController = ProfileViewController(nibName: nil, bundle: nil)
let tabBarController = UITabBarController()
self.window!.rootViewController = tabBarController
tabBarController.viewControllers = [feedViewController, favoritesViewController, profileViewController]
self.window!.backgroundColor = UIColor.whiteColor()
self.window!.makeKeyAndVisible()
return true
}
答案 0 :(得分:2)
导航控制器对象self.navigationController
nil
?
navigationController
属性上的变量类型是一个未包装的可选项。如果您的View Controller不在UINavigationController
内,那将是问题。
为防止崩溃代码沿着以下行写入:
if (self.navigationController)
{
self.navigationController.pushViewController(profileViewController, animated: true)
}
或者您可以将代码编写为:
self.navigationController?.pushViewController(profileViewController, animated: true)
如果?
评估为self.navigationController
,nil
运算符将阻止执行任何进一步的代码。