在我的appDelegate类中,我创建了一个UITabController,其中我添加了4个tableViewController作为tabBarController的项目。目标是有 4 个项目使用单个版本的 tableViewController。
下面是设置 tableView 控制器并将其添加到 tabBar 控制器的代码部分
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
window = UIWindow(frame: UIScreen.main.bounds)
let controller1 = setUpViewControllers(title: "Item 1")
let controller2 = setUpViewControllers(title: "Item 2")
let controller3 = setUpViewControllers(title: "Item 3")
let controller4 = setUpViewControllers(title: "Item 4")
// Set up the tab bar controller
let tabController = UITabBarController()
tabController.setViewControllers([controller1,controller2,controller3,controller4], animated: true)
// use the tab bar controller as the root view controller
window?.rootViewController = tabController
window?.makeKeyAndVisible()
return true
}
以下是创建表视图控制器的函数的定义
func setUpViewControllers(title : String) -> MyTableViewController {
let vc = MyTableViewController();
vc.tabBarItem.title = title
return vc
}
在我的表视图控制器中,
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let model = listOfData[indexPath.row]
let currentRow = indexPath.row
let cell = tableView.dequeueReusableCell(withIdentifier: "cellIdentifier", for: indexPath) as! CustomCell
// the error starts when the code reaches this part, the properties of the cell:
// title and details are nil
cell.title.text = model.title
cell.details.text = model.details
return cell
}
上面代码中使用的单元格,它是我在情节提要中设计的单元格,并将其视图链接到 UITableViewCell 的子类
import UIKit
class CustomCell: UITableViewCell {
@IBOutlet weak var title: UILabel!
@IBOutlet weak var details: UILabel!
}
起初,当我启动该应用程序时,我遇到了以下异常
NSInternalInconsistencyException', reason: 'unable to dequeue a cell with identifier cellIdentifier - must register a nib or a class for the identifier or connect a prototype cell in a storyboard'
我尝试按照异常的消息说,我在tableView控制器的viewDidLoad((中注册了我的自定义单元格
self.tableView.register(CustomCell.self, forCellReuseIdentifier: "cellIdentifier")
这一次,例外消失了,但我无法访问我的单元格视图,因为它们都是零。 我不知道为什么它不起作用。
您没有从故事板实例化MyTableViewController
...您只是在创建类的实例。
您的setUpViewControllers
功能需要看起来像这样:
func setUpViewControllers(title : String) -> MyTableViewController {
let storyboardName = "Main"
let controllerID = "MyTableViewController"
let sb = UIStoryboard(name: storyboardName, bundle: nil)
guard let vc = sb.instantiateViewController(withIdentifier: controllerID) as? MyTableViewController else {
fatalError("Couldn't instantiate MyTableViewController")
}
vc.tabBarItem.title = title
return vc
}
如果控制器位于"主"以外的情节提要中,则相应地更改它以及控制器的情节提要 ID。
编辑- 那么你也不应该需要self.tableView.register(CustomCell.self, forCellReuseIdentifier: "cellIdentifier")
行。