gpt4 book ai didi

swift - 无法将表达式的类型 '()' 转换为类型 'UINavigationController?'

转载 作者:行者123 更新时间:2023-11-28 05:33:54 25 4
gpt4 key购买 nike

我无法解决 AppDelegate.swift 中的错误。

我收到一条消息“无法将表达式的类型‘()’转换为类型‘UINavigationController?’

有人给我建议吗?

import UIKit

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

var window: UIWindow?


func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
window = UIWindow(frame: UIScreen.mainScreen().bounds)

let tabBarController = UITabBarController()
let alarmViewController = AlarmViewController(style: .Plain)
let recorderViewController = RecorderViewController()
let playViewController = PlayViewController()

let tabController1 = UINavigationController(rootViewController: recorderViewController)
tabController1?.tabBarItem = UITabBarItem(title: "Recorder", image: UIImage(named: "tabbar_microphone"), tag: 1)

let tabController2 = UINavigationController(rootViewController: playViewController)
tabController2?.tabBarItem = UITabBarItem(title: "Cheer me up!", image: UIImage(named: "tabbar_play"), tag: 2)

let tabController3 = UINavigationController(rootViewController: alarmViewController!)
tabController3?.tabBarItem = UITabBarItem(title: "Alarm", image: UIImage(named: "tabbar_alarm"), tag: 3)

******* here's a place I got the message 'Cannot convert the expression's type '()' to type 'UINavigationController?' *******
tabBarController.viewControllers = [tabController1, tabController2, tabController3]

window?.rootViewController = tabBarController
window?.makeKeyAndVisible()
return true
}

最佳答案

您的 tabControllerX 都是可选的(正如您似乎意识到的那样,因为您在分配 UITabBarItem 时将它们全部引用为 ? )所以你需要打开它们。考虑到您的结构,最简单的方法就是简单地更改行

tabBarController.viewControllers = [tabController1!, tabController2!, tabController3!]
// Unwrap tabControllers

我会用不同的方式来做,因为我不喜欢在我的逻辑中有可选项,而不知道它们是否为 nil,比如

if let tabController1 = UINavigationController(rootViewController: recorderViewController)
// Now you know it's a tabController!
tabController1.tabBarItem = UITabBarItem(title: "Recorder", image: UIImage(named: "tabbar_microphone"), tag: 1)
// ...
} else {
// what are you going to do if it's nil?
}

关于swift - 无法将表达式的类型 '()' 转换为类型 'UINavigationController?',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26071284/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com