ios - 在 Master-Detail 应用程序中为 Master/Detail View Controller 重用 UIViewController(带有 UITableView)?
问题描述
我正在使用这个Ray Wenderlich 教程作为我正在从事的项目的指南。但是,我正在尝试扩展此模板以合并子目录、子子目录、子子子目录等。
例如,如果您单击主/主目录屏幕中的“Candy Cane”单元格,它将带您进入带有表格视图(也称为子目录屏幕)的“新”视图控制器,其中将显示各种 Candy Cane 供应商以及它们的价格是贵还是便宜(这将是每一行的副标题)。请参阅subCategory
下面的 ... txt 文件。
我在这篇文章中交替使用了类别和目录这两个词。
这是第一个问题。过去,我创建了一个项目来做这件事,但是我通过许多故事板和视图控制器文件来完成我导航的每个子类别的工作。同样的原则也适用于从子类别移动到子子类别屏幕等等。
我不想做广告:但具体来说,我正在开发的应用程序叫做iEngineering,它可以在 AppStore 上免费获得。请查看应用程序的库部分,因为我相信它会为理解我的最终目标提供额外帮助。请记住,当前版本的应用程序是使用无数故事板和视图控制器文件构建的,每次我在 Xcode 中运行模拟器时都必须构建这些文件。查看显示库功能的应用程序屏幕截图就足够了,而无需下载应用程序。
这是第二个问题。我在这个应用程序中也有子子类别等等。例如,如果您单击子类别屏幕中显示拐杖糖供应商和价格列表的单元格,它会将您导航到一个新屏幕(子子类别),以显示该特定供应商的所有不同拐杖糖销售量。因此,在下面我编写的文本文件中subCandyCaneTextFile.txt
,如果您单击带有“Candy Cane King”标签的单元格,它将带您进入一个显示“Candy Cane King”作为导航标题的屏幕,并显示/加载一个清单(通过阅读文本文件导入)显示 Candy Cane King 提供的所有棒棒糖。我没有提供我认为是子类别的这个和其他 txt 文件. 当我在下面问我问题的根本/核心时,我希望你们都记住这一点。
对于这个项目,我想远离使用带有许多视图控制器的多个故事板。这是因为每次我在模拟器中构建它时,我之前的项目都需要大约 5 到 10 分钟来编译/构建。因此,我试图在项目运行时为我的应用程序中的每个新/类别屏幕读取文本文件。我希望这会给我带来更快的运行时间(约 10 秒)。
在下面的示例中,类别/主视图控制器通过读取 txt 文件来呈现其数据candyTextFile.txt
我的问题:我怎样才能为子类别屏幕处理(从|删除)旧数据和(加载|替换)新数据?我曾想过尝试将其作为Ray Wenderlich 教程教程中的 Detail View Controller 屏幕;但是,我不确定如何导航到子子类别屏幕。因此,我认为我的另一个选择可能是一遍又一遍地使用 UITableView(主视图控制器)重用一个视图控制器。我不确定解决这个问题的正确方法,因为我对学习 Swift 和 Xcode 还比较陌生。
本文通过 Xcode概述当前项目。
在我的 MasterViewController.swift 中,
import UIKit
class MasterViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
// MARK: - Properties
@IBOutlet var tableView: UITableView!
@IBOutlet var searchFooter: SearchFooter!
var detailViewController: DetailViewController? = nil
var candies = [Candy]()
var filteredCandies = [Candy]()
let searchController = UISearchController(searchResultsController: nil)
// MARK: - View Setup
override func viewDidLoad() {
super.viewDidLoad()
// Setup the Search Controller
searchController.searchResultsUpdater = self
searchController.obscuresBackgroundDuringPresentation = false
searchController.searchBar.placeholder = "Search Candies"
navigationItem.searchController = searchController
definesPresentationContext = true
// Setup the Scope Bar
searchController.searchBar.scopeButtonTitles = ["All", "Chocolate","Hard", "Other"]
searchController.searchBar.delegate = self
// Setup the search footer
tableView.tableFooterView = searchFooter
setupArray()
if let splitViewController = splitViewController {
let controllers = splitViewController.viewControllers
detailViewController = (controllers[controllers.count-1] as! UINavigationController).topViewController as? DetailViewController
}
}
private func setupArray() {
if let filepath = Bundle.main.path(forResource: "candyTextFile", ofType: "txt") {
do {
let contents = try String(contentsOfFile: filepath)
let lines_separatedBy_n : [String] = contents.components(separatedBy: "\n")
let string = lines_separatedBy_n.map { String($0) }.joined(separator: ", ")
var lines_separatedBy_comma : [String] = string.components(separatedBy: ", ")
// I've put this in to remove the last bit of the file that was causing the count to be one too high.
// I'm guessing that's why you had something similar previously?
lines_separatedBy_comma.removeLast()
for (index, element) in lines_separatedBy_comma.enumerated() {
if index % 2 == 0 {
let newCategory = element
let newName = lines_separatedBy_comma[index + 1]
let newCandy = Candy(category: newCategory, name: newName)
candies.append(newCandy)
}
}
for candy in candies {
print("category: \(candy.category), name: \(candy.name)")
}
//("\ncandies: \(candies)")
} catch let error as NSError {
print(error.localizedDescription)
}
}
print("\ncandies: \(candies)")
}
override func viewWillAppear(_ animated: Bool) {
print("splitViewController!.isCollapsed: \(splitViewController!.isCollapsed)")
if splitViewController!.isCollapsed {
if let selectionIndexPath = tableView.indexPathForSelectedRow {
tableView.deselectRow(at: selectionIndexPath, animated: animated)
}
}
super.viewWillAppear(animated)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
// MARK: - Table View
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if isFiltering() {
print("Is filtering")
searchFooter.setIsFilteringToShow(filteredItemCount: filteredCandies.count, of: candies.count)
return filteredCandies.count
}
print("Is not filtering")
searchFooter.setNotFiltering()
return candies.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
let candy: Candy
if isFiltering() {
candy = filteredCandies[indexPath.row]
} else {
candy = candies[indexPath.row]
}
cell.textLabel!.text = candy.name
cell.detailTextLabel!.text = candy.category
return cell
}
// MARK: - Segues
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "showDetail" {
if let indexPath = tableView.indexPathForSelectedRow {
let candy: Candy
if isFiltering() {
candy = filteredCandies[indexPath.row]
} else {
candy = candies[indexPath.row]
}
let controller = (segue.destination as! UINavigationController).topViewController as! DetailViewController
controller.detailCandy = candy
controller.navigationItem.leftBarButtonItem = splitViewController?.displayModeButtonItem
controller.navigationItem.leftItemsSupplementBackButton = true
}
}
}
func filterContentForSearchText(_ searchText: String, scope: String = "All") {
filteredCandies = candies.filter({
(candy : Candy) -> Bool in
let doesCategoryMatch = (scope == "All") || (candy.category == scope)
if searchBarIsEmpty(){
return doesCategoryMatch
}else {
return doesCategoryMatch && candy.name.lowercased().contains(searchText.lowercased())
}
})
tableView.reloadData()
}
func searchBarIsEmpty() -> Bool {
return searchController.searchBar.text?.isEmpty ?? true
}
func isFiltering() -> Bool {
let searchBarScoperIsFiltering = searchController.searchBar.selectedScopeButtonIndex != 0
return searchController.isActive && (!searchBarIsEmpty() || searchBarScoperIsFiltering)
}
}
extension MasterViewController: UISearchBarDelegate {
// MARK: - UISearchBar Delegate
func searchBar(_ searchBar: UISearchBar, selectedScopeButtonIndexDidChange selectedScope: Int) {
filterContentForSearchText(searchBar.text!, scope: searchBar.scopeButtonTitles![selectedScope])
}
}
extension MasterViewController: UISearchResultsUpdating {
// MARK: - UISearchBar Delegate
func updateSearchResults(for searchController: UISearchController) {
let searchBar = searchController.searchBar
let scope = searchBar.scopeButtonTitles![searchBar.selectedScopeButtonIndex]
filterContentForSearchText(searchController.searchBar.text!, scope: scope)
}
}
在 candyTextFile.txt 中,
Chocolate, Chocolate Bar
Chocolate, Chocolate Chip
Chocolate, Dark Chocolate
Hard, Lollipop
Hard, Candy Cane
Hard, Jaw Breaker
Other, Caramel
Other, Sour Chew
Other, Gummi Bear
Other, Candy Floss
Chocolate, Chocolate Coin
Chocolate, Chocolate Egg
Other, Jelly Beans
Other, Liquorice
Hard, Toffee Apple
在 subCandyCaneTextFile.txt 中,
Cheap, Brachs
Expensive, Spangler
Expensive, Bobs
Cheap, Candy Cane King
Expensive, Jelly Belly
其他子类别文件:
在 subDarkChocolateTextFile.txt 中,
Cheap, Ghirardelli
Expensive, Dove
Expensive, Lindt
Cheap, Hersheys
Expensive, Hu Dark
在 subLollipopTextFile.txt 中,
Cheap, Zollipops
Cheap, YumEarth
Expensive, Dum Dums
谢谢大家的时间和你们可能提供的任何指导。我非常感激。
解决方案
您可以DetailViewController
从同一个情节提要中重复使用。为其分配一个Storyboard ID
,然后您可以DetailViewController
从当前实例创建新的类实例。您可以保留新 VC 的索引,例如递增它并使用它例如从预定义的数组中获取下一个类别文件名并将其加载到例如viewDidLoad
在DetailViewController
课堂上:
var index = 0;
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let st = UIStoryboard(name: "Main", bundle: nil)
let vc = st.instantiateViewController(withIdentifier: "DetailViewController") as! DetailViewController
vc.index = self.index + 1;
self.navigationController?.pushViewController(vc, animated: true)
}
编辑
如何使用索引
用你的文件名声明数组:let files = ["file1", "file2", "file3"]
在setupArray()
使用中
if let filepath = Bundle.main.path(forResource: files[index], ofType: "txt")
推荐阅读
- javascript - 如何检查窗口是否从 window.open() 实例化
- apache-kafka - 在所有代理关闭后,kafka 没有将副本分配为领导者
- c# - CMake 中构建后自定义命令中的 Glob 文件
- php - 如何在我的数组编辑中调用这个变量
- angular - Datatable.net 分页按钮单击的回调函数
- python - python中的问题,同时结合2个文本文件并将它们总结成一个新的文本文件
- json - 我正在尝试使用 swift 4 解析 json,请告诉我其中有什么问题?
- javascript - React Native:图像未使用动态/本地 URI 显示
- tsql - 如何将多行子查询的行与要在 T-sql 中的 In 中使用的条件语句组合起来
- yii - Yii 渲染法语显示特殊字符的视图文件