本质上,我试图在选择特定行时更改变量,但代码仍在打印-1。这是我所有的相关代码。我正在尝试单击某个表视图单元格,然后打印出该文本。searchBar会影响我的值吗?我首先编写了表视图,然后编写了搜索栏,然后实现了一个提交按钮,它可以打印变量的值。
class ViewController: UIViewController, UITableViewDataSource, UISearchBarDelegate, UITableViewDelegate {
@IBOutlet weak var searchBar: UISearchBar!
@IBOutlet weak var tableView: UITableView!
let Data = ["dog","cat","goat"]
var filteredData: [String]!
var num = -1
var animal: String = ""
override func viewDidLoad() {
super.viewDidLoad()
if tableView != nil {
self.tableView.dataSource = self
}
filteredData = Data
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as UITableViewCell
cell.textLabel?.text = filteredData[indexPath.row]
print(indexPath.row)
return cell
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return filteredData.count
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if indexPath.row == 0 {
num = 0
}
if indexPath.row == 1 {
num = 1
}
if indexPath.row == 2 {
num = 2
}
}
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
filteredData = searchText.isEmpty ? Data : Data.filter { (item: String) -> Bool in
// If dataItem matches the searchText, return true to include it
return item.range(of: searchText, options: .caseInsensitive, range: nil, locale: nil) != nil
}
tableView.reloadData()
}
func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) {
self.searchBar.showsCancelButton = true
}
func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
searchBar.showsCancelButton = false
searchBar.text = ""
searchBar.resignFirstResponder()
}
@IBAction func Submit(_ sender: Any) {
print(num)
print(filteredData.count)
if num == 0 {
animal = "dog"
}
if num == 1 {
animal = "cat"
}
if num == 2 {
animal = "goat"
}
print(animal)
}
}
有几个问题不能让你实现你想要的:
==
运算符检查两个变量是否相等,而不是将一个变量分配给另一个变量,它将返回一个布尔值true
或false
。在if
语句的正文中,将==
更改为=
,为变量num.赋值
将您的代码更改为:
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if indexPath.row == 0 {
num = 0
}
if indexPath.row == 1 {
num = 1
}
if indexPath.row == 2 {
num = 2
}
}
看到更新后的代码后,您似乎只设置了tableView的dataSource
,而没有设置委托。您需要将该行添加到viewDidLoad
:
tableView.delegate = self
此外,您可以用一行代码替换整个代码体:,而不是用多个if
语句来检查indexPath
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
num = indexPath.row
}