<分区>
所以我是初学者,刚开始学习swift。我在使用数组和 tableView 时遇到问题。基本上我有两个数组。一个有水果+蔬菜的所有名称,而另一个数组有每个名称的描述。 我已经能够将该数组中的所有水果显示为表格。现在我希望在按下某个单元格时显示正确的描述。因此,例如,当我按下 Apple 时,我想要显示它的简短描述。 我正在使用这个功能:
func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath)
{
myIndex = indexPath.row
print(myIndex)
}
然后我使用 myIndex 变量来存储所选项目的索引号。现在只是为了测试,我正在打印 myindex 并且我得到了所有错误的索引号。对于第二项而不是 1,我得到 2,在其他情况下,它不为我提供第一项的索引,而是从第二项开始。
我在这里做错了什么。我打算使用这个 indexpath.row 并显示相应项目的描述。
任何帮助就足够了。
代码如下:
var list = ["Apple", "Oranges", "Mangoes"]
var detaillist = ["Red", "Orange is Orange", "Mangoes are yellow"]
var myIndex = 0
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
@IBOutlet weak var myTableView: UITableView!
public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return(list.count)
}
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
let cell = UITableViewCell(style: UITableViewCellStyle.default, reuseIdentifier: "cell")
cell.textLabel?.text = list[indexPath.row]
return(cell)
}
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath)
{
if editingStyle == UITableViewCellEditingStyle.delete
{
list.remove(at: indexPath.row)
myTableView.reloadData()
}
}
func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath)
{
myIndex = indexPath.row
print(myIndex)
}
override func viewDidAppear(_ animated: Bool) {
myTableView.reloadData()
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}