- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
这是我的情况:我在导航器中有一个 TableView ,其中包含 4 个部分,每个部分都有一定数量的单元格。我想使用搜索栏来查看我的表格 View 的内容,但我无法按照我的意愿这样做,而且我所遵循的教程仅描述了 1 个表格 View ,其中包含 1 个部分和一个“n"的行数,但与具有 n 个部分和每个部分 m 行的 TableView 无关。我发现的那些还没有答案。所以我想请你们帮忙了解如何在我之前提到的条件下实现搜索栏。
正如我之前介绍的,我有一个包含 4 个部分和每个部分中一些单元格的 TableView ,当我单击一个单元格时,它会将我带到另一个 View Controller ,该 View Controller 具有显示该部分和行的数据的 textView。我想实现一个搜索栏,这样用户就不必在整个表格 View 中向下滚动来找到他/她需要的东西,但到目前为止,我还没有找到使用带有部分的搜索栏的教程/示例,他们使用带有一个部分和许多单元格的单个表格 View 。我已经尝试实现 SearchBarDelegate(使用我找到的教程),但它没有像我预期的那样工作。所以我来找你,看看你是否可以分享你的一些知识和智慧来帮助我解决这个问题。
这是我的 tableViewController 的代码(/* */之间的代码是没有实现 searchBar 的代码,所以它只会显示带有部分和单元格的 TableView ):
import UIKit
class TableViewController: UITableViewController {
// MARK: - Variables and Constants
var selectedIndex = Int()
var selectedSection = Int()
var textKind = [
["""
SECTION 1, ROW 0 \n
Esto debe venir de section 1 row 0, y para hacerlo realmente largo es necesario meter un montón de cosas irrelevantes para ver si respeta los espacios y los renglones del textView. Gracias de nada.
""",
"""
SECTION 1, ROW 1 \n
Esto debe venir de section 1 row 1. Una vez más es necesario asegurarse de que los márgenes y formatos de texto son respetados. De otro modo habrá que corregirlos. \n
Aquí hay un salto de línea. A ver qué tal sale.
""",
"""
SECTION 1, ROW 2 \n
Esto debe venir de section 1 row 2. \n \n
OTRO SUBTÍTULO DENTRO DE LA SECCIÓN. \n
Se usarán 2 nuevas líneas cuando haya que añadir algún título o subtítulo dentro del textView. Por cuestiones de estética visual.
""",
"""
SECTION 1, ROW 3 \n
Esto debe venir de section 1 row 3
"""],
["""
SECTION 2 ROW 0 \n
Esto debe venir de section 2 row 0. Lorem ipsum dolor sit er elit lamet, consectetaur cillium adipisicing pecu, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Nam liber te conscient to factor tum poen legum odioque civiuda. \n \n \n \n \n \n
Aquí sigue la onda pedorra.
""",
"Esto debe venir de section 2 row 1",
"Esto debe venir de section 2 row 2",
"Esto debe venir de section 2 row 3",
"Esto debe venir de section 2 row 4",
"Esto debe venir de section 2 row 5",
"Esto debe venir de section 2 row 6"],
["Esto debe venir de section 3 row 0",
"Esto debe venir de section 3 row 1",
"Esto debe venir de section 3 row 2"],
["Esto debe venir de section 4 row 0",
"Esto debe venir de section 4 row 1",
"Esto debe venir de section 4 row 2",
"Esto debe venir de section 4 row 3",
"Esto debe venir de section 4 row 4",
"Esto debe venir de section 4 row 5",
"Esto debe venir de section 4 row 6",
"Esto debe venir de section 4 row 7"]
]
var sectionsNames:[String] = ["section 1", "section 2", "section 3" , "section 4"]
var section1Content:[String] = ["uno", "dos", "tres", "cuatro"]
var section2Content:[String] = ["a", "be", "ce", "de", "e", "efe", "ge"]
var section3Content:[String] = ["alpha", "beta", "gamma"]
var section4Content:[String] = ["ichi", "ni", "san", "shi", "go", "roku", "nana", "hachi"]
@IBOutlet weak var searchBarVariable: UISearchBar!
var searching = false
var searchingData = [String]()
// MARK: - viewDidLoad()
override func viewDidLoad() {
super.viewDidLoad()
searchBarVariable.delegate = self
}
// MARK: - TableView configuration (sections, cellForRowAt, etc.).
// MARK: - Number of sections
override func numberOfSections(in tableView: UITableView) -> Int {
return sectionsNames.count
}
// MARK: - Sections' titles
override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return sectionsNames[section]
}
// MARK: - Number of rows per section
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if searching {
return searchingData.count
} else {
switch section {
case 0:
return section1Content.count
case 1:
return section2Content.count
case 2:
return section3Content.count
case 3:
return section4Content.count
default:
return 0
}
}
/* switch section {
case 0:
return section1Content.count
case 1:
return section2Content.count
case 2:
return section3Content.count
case 3:
return section4Content.count
default:
return 0
} */
}
// MARK: - Cells' content
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = self.tableView.dequeueReusableCell(withIdentifier: "sourceCell", for: indexPath)
if searching {
cell.textLabel?.text = searchingData[indexPath.row]
} else {
switch indexPath.section {
case 0:
cell.textLabel!.text = section1Content[indexPath.row]
case 1:
cell.textLabel!.text = section2Content[indexPath.row]
case 2:
cell.textLabel!.text = section3Content[indexPath.row]
case 3:
cell.textLabel!.text = section4Content[indexPath.row]
default:
break
}
}
/*switch indexPath.section {
case 0:
cell.textLabel!.text = section1Content[indexPath.row]
case 1:
cell.textLabel!.text = section2Content[indexPath.row]
case 2:
cell.textLabel!.text = section3Content[indexPath.row]
case 3:
cell.textLabel!.text = section4Content[indexPath.row]
default:
break
} */
return cell
}
// MARK: - DidSelectRowAt
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
self.selectedSection = indexPath.section
self.selectedIndex = indexPath.row
performSegue(withIdentifier: "goToInfo", sender: self)
}
// MARK: - prepare(for segue:...)
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "goToInfo" {
let vc: ViewController = segue.destination as! ViewController
vc.viewTextText = textKind[self.selectedSection][self.selectedIndex]
print(vc.viewTextText)
}
}
}
// MARK: - Searchbar in tableview
extension TableViewController: UISearchBarDelegate {
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
searchingData = section1Content.filter({$0.lowercased().prefix(searchText.count) == searchText.lowercased()}) + section2Content.filter({$0.lowercased().prefix(searchText.count) == searchText.lowercased()}) + section3Content.filter({$0.lowercased().prefix(searchText.count) == searchText.lowercased()}) + section4Content.filter({$0.lowercased().prefix(searchText.count) == searchText.lowercased()})
searching = true
tableView.reloadData()
}
func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
searching = false
searchBar.text = ""
tableView.reloadData()
}
}
这是链接到之前的 tableViewController 的 viewController 的代码:
import UIKit
class ViewController: UIViewController {
//MARK: - Variables and Constants
var viewTextText:String = ""
// MARK: - ViewController components
@IBOutlet weak var scrollView: UIScrollView!
@IBOutlet weak var viewTextViewText: UITextView!
@IBOutlet weak var imageView: UIImageView!
// MARK: - viewDidLoad()
override func viewDidLoad() {
super.viewDidLoad()
arrangingTextView()
}
func arrangingTextView() {
self.viewTextViewText.text = viewTextText
self.viewTextViewText.font = UIFont(name: "helvetica", size: 24.0)
self.viewTextViewText.textAlignment = .justified
}
}
预期结果:在搜索栏中输入时,必须仅显示搜索栏中匹配输入的部分和单元格。当我点击想要的信息时,它应该将我带到包含该部分和单元格信息的 viewController。
实际情况:在搜索栏中输入时,它会在 4 个部分及其内容中显示相同的内容。当我点击该行时,我会看到与该单元格无关的虚假信息。
如果您重现我的代码,您会更好地理解我的意思。
最佳答案
这种做法是不合适的。无需使用标志变量作为搜索
和处理不同的场景,您需要做的只是为整个过程定义一个数组。在您的情况下,您的数据源数组将如下所示:
[["uno", "dos", "tres", "cuatro"],["a", "be", "ce", "de", "e", "efe", "ge"],["alpha", "beta", "gamma"],["ichi", "ni", "san", "shi", "go", "roku", "nana", "hachi"]]
现在,一切都更容易处理和实现。例如,行数委托(delegate)函数中的 switch case 将被替换为:
return dataSource[section].count
您在这里要做的是在点击搜索结果时将两个不同的数组相互映射。当你有多个与一件事相关的属性时,我建议你创建一个类:
struct Item {
var title : String // this is cell's title
var text : String // this is what will be shown on the next view controller when a cell is tapped.
}
您的数据源将如下所示:
var dataSource : [[Item]] = [[Item(title: "uno" , text: """
SECTION 1, ROW 0 \n
Esto debe venir de section 1 row 0, y para hacerlo realmente largo es necesario meter un montón de cosas irrelevantes para ver si respeta los espacios y los renglones del textView. Gracias de nada.
""") , Item(title: "dos" , text: """
SECTION 1, ROW 1 \n
Esto debe venir de section 1 row 1. Una vez más es necesario asegurarse de que los márgenes y formatos de texto son respetados. De otro modo habrá que corregirlos. \n
Aquí hay un salto de línea. A ver qué tal sale.
""" ) , Item(title: "tres" , text: """
SECTION 1, ROW 2 \n
Esto debe venir de section 1 row 2. \n \n
OTRO SUBTÍTULO DENTRO DE LA SECCIÓN. \n
Se usarán 2 nuevas líneas cuando haya que añadir algún título o subtítulo dentro del textView. Por cuestiones de estética visual.
""" ), Item(title: "cuatro" , text: """
SECTION 1, ROW 3 \n
Esto debe venir de section 1 row 3
""" )] , [Item(title: "a" , text: """
SECTION 2 ROW 0 \n
Esto debe venir de section 2 row 0. Lorem ipsum dolor sit er elit lamet, consectetaur cillium adipisicing pecu, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Nam liber te conscient to factor tum poen legum odioque civiuda. \n \n \n \n \n \n
Aquí sigue la onda pedorra.
""" ) , Item(title: "be" , text: "Esto debe venir de section 2 row 1" ) , Item(title: "ce" , text: "Esto debe venir de section 2 row 2" ) , Item(title: "de" , text: "Esto debe venir de section 2 row 3" ) , Item(title: "e" , text: "Esto debe venir de section 2 row 4" ) , Item(title: "efe" , text: "Esto debe venir de section 2 row 1" ) , Item(title: "ge" , text: "Esto debe venir de section 2 row 5" )]]
现在,在您的搜索委托(delegate)函数中,您需要根据文本从数据源数组中删除不需要的结果,或者在点击取消按钮时将数组重置为默认值。完成后,您需要做的就是重新加载 TableView :
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
self.dataSource = values
var filteredDataSource : [[Item]] = []
for items in dataSource {
let filteredItems = items.filter { (item) -> Bool in
if item.title.lowercased().prefix(searchText.count) == searchText.lowercased() {
return true
}
return false
}
filteredDataSource.append(filteredItems)
}
self.dataSource = filteredDataSource
tableView.reloadData()
}
func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
self.dataSource = values //reseting data source to defaults
tableView.reloadData()
}
当您选择一行时,您在代码中错误地传递了节和行号。为了将相应的数据适本地传递给下一个 View Controller ,您需要在 prepare for segue 函数中执行此操作:
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
//assuming your next view controller class's name is ViewController.
guard let detailViewController = segue.destination as? ViewController,
let row = tableView.indexPathForSelectedRow?.row,
let section = tableView.indexPathForSelectedRow?.section
else {
return
}
detailViewController.item = dataSource[section][row] //passing selected item object.
}
最后,在您的下一个 View Controller 中,您将拥有同时具有标题和文本属性的项目对象。在您的情况下,您想要显示其文本属性。希望对您有所帮助!
编辑
关于 github 的完整解决方案.
关于ios - 如何在具有多个部分的 TableView 中使用 searchBar?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57756260/
我正在对 tableView 是否呈现单元格进行单元测试。 我发现 tableView.cellForRow(at:) 返回 nil,而 tableView.dataSource?tableView(
我有 Tableview 用于显示客户下的食品订单。其中包含水平 UIStackview。在 UIStackView UIStackview 中很少有一/两行标签和一个用于显示订单项的UITableV
我有 Viewcontroller,我在其中设置了 ScrollView 。在 scrollview 中,我有一个 tableview,它位于 Container 中,就在容器下方,当我将 table
我想在滚动时让我的第一个单元格始终位于 tableview 的顶部。 任何帮助都是可观的。提前致谢... 最佳答案 这是为 UITableView 创建标题 View 的方法 - (UIView *)
在我的应用程序中,我点击一行,它会在其下方展开另一行。我想生成一种随机颜色,当我单击一行时,行背景会变成该颜色,而它下面的展开行会变成相同的颜色。如何让行生成相同的随机颜色? 我创建了一个函数来生成随
我正在为这个问题苦苦挣扎,所以我需要你的帮助。基本上我已经编写了一个复杂的 TableView Controller (使用 NSFetchedResults 协议(protocol)等)并且已经在我
我正在使用 JavaFx 2.2。我遇到了一个问题,我无法在 TableView 列中放置不同的组件。例如我有两列 1) 回答 2) 答案类型 如果 AnswerType 包含“Multiple Ch
试图弄清楚如何在 javafx 2 中禁用表列的重新排序? 最佳答案 这是解决方案: tblView.getColumns().addListener(new ListChangeListener()
我一直在寻找有关将数据刷新到 tableview 的信息。我试图直接修改模型,但我遇到了一个错误。我修改了模型,但表格没有刷新,只有当我移动一列时,表格才会显示修改后的值。 为了给你展示一个例子(13
给定一个TableView,我需要检测单元格上的双击。 tableView.setOnMouseClicked(new EventHandler() { @Override publi
我成功创建了一个 TableView,其中将特定列分配给了数据模型类。该程序可以将 csv 文件解析为其中并在表中正确显示所有内容。在此阶段,滚动不是问题。 然后我想选择特定行并将它们发送到另一个表。
我尝试了所有方法来用数据填充 TableView。下一个代码在表中插入一个新行,但数据没有出现在表中。我试图为此找到解释,但没有成功。 请帮忙。我不知道怎么了。 在 controller.java 中
我尝试了所有方法来用数据填充 TableView。下一个代码在表中插入一个新行,但数据没有出现在表中。我试图为此找到解释,但没有成功。 请帮忙。我不知道怎么了。 在 controller.java 中
我有一个通过 Tableview 显示玩家的应用程序。用户可以“添加”一个新玩家并输入他的姓名、高度、体重、图片等...保存后将被添加到 Tableview 中。他们还可以点击每个玩家,然后将他们带到
对于大学,我必须编写一个小应用程序,其想法是创建一个小公式集合。这个概念是有一个类别列表,选择类别后您会收到一个公式列表。选择所需的公式后,您将看到公式计算器的 View 。 我正在努力获得第一个UI
如果我只加载一个 TableView ,我的 View 中必须有两个 TableView ,它工作正常。但是当我尝试使用下面的方法加载两个表格 View 时,它给出了以下异常。 未捕获异常“NSRan
我是 JavaFx 的新手,我正在尝试创建一个 TableView ,而 fxml 是使用场景生成器创建的。如果我运行该程序,该表不会获取值。我发现这个问题在某种程度上符合我的要求( javaFX 2
是否可以对 tableView 进行反向排序?我搜索了很多解决方案,但没有任何效果。 效果就像whatsapp聊天。 一个普通的tableView是: ---------- label 1 -----
我有一个有趣的问题。我有两个 TableView ,一个在另一个里面。我有一个结构,我想用它来将数据添加到我的 TableView 中。该结构有 2 个字符串项和另一个具有 3 个字符串项的结构的数组
我正在使用的方法 func tableView(tableView: UITableView, editActionsForRowAtIndexPath indexPath: NSIndexPath
我是一名优秀的程序员,十分优秀!