【发布时间】:2020-05-21 11:15:21
【问题描述】:
现在我有一个表格视图,它有一个基本样式的动态单元格。目前,名称列表显示在表格视图中,但我想使用 didSelectRowAt 函数为每一行创建新的详细视图。每次从我的表格视图中选择某一行时,我将如何创建一个可自定义的新视图控制器?此外,我的故事板通过名为“show”的 segue 从单元连接到另一个名为“SecondViewController”的视图控制器。
这是我到目前为止的代码。
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var searchBar: UISearchBar!
@IBOutlet weak var tableView: UITableView!
struct Data {
var sectionTitle = String()
var rowTitles = [String]()
}
var dataArray = [Data(sectionTitle: "section 1", rowTitles: ["row 1", "row 2"]),
Data(sectionTitle: "section 2", rowTitles: ["row 1", "row 2", "row 3"]),
Data(sectionTitle: "section 3", rowTitles: ["row 1"])
]
var searchArray = [Data]()
var searching = false
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
<#code#>
}
}
extension ViewController: UITableViewDelegate, UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if searching {
return searchArray[section].rowTitles.count
} else {
return dataArray[section].rowTitles.count
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "searchCell")
cell?.textLabel?.lineBreakMode = NSLineBreakMode.byWordWrapping
cell?.textLabel?.numberOfLines = 3
if searching {
cell?.textLabel?.text = self.searchArray[indexPath.section].rowTitles[indexPath.row]
} else {
cell?.textLabel?.text = self.dataArray[indexPath.section].rowTitles[indexPath.row]
}
return cell!
}
func numberOfSections(in tableView: UITableView) -> Int {
if searching {
return searchArray.count
} else {
return dataArray.count
}
}
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return dataArray[section].sectionTitle
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
self.performSegue(withIdentifier: "show", sender: self)
}
}
extension ViewController: UISearchBarDelegate {
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
if searchBar.text == nil || searchBar.text == "" {
searching = false
view.endEditing(true)
tableView.reloadData()
} else {
searching = true
searchArray = dataArray.filter({$0.sectionTitle.lowercased().contains(searchBar.text!.lowercased()) || $0.rowTitles.map{$0.lowercased()}.contains(searchBar.text!.lowercased())})
tableView.reloadData()
}
}
}
【问题讨论】:
-
你是在问如何用数据初始化一个新的 viewController 并将其显示或推送到堆栈上吗?
-
是否要将选定的数据模型传递给 SecondViewController?
-
是的。我将如何获取任何 tableview 单元并将其推送到自定义 viewController?
-
我不想将任何数据传递给 SecondViewController。
-
请不要命名自定义结构
Data。它可能会干扰具有相同名称的 Foundation 结构。Section怎么样?然后你甚至可以用title重命名sectionTitle
标签: ios swift xcode uitableview