问题描述
本质上,当我选择了特定的行时,我试图更改变量,但是代码仍在打印-1。这是我所有与之相关的代码。我试图能够单击某个tableview单元格,然后能够打印出该文本。 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
}