ios - Index.path 没有返回正确的索引

标签 ios arrays swift

<分区>

所以我是初学者,刚开始学习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.
}

最佳答案

将您的选择功能更改为-:

 func tableView(_ tableView: UITableView, 
         didSelectRowAt indexPath: IndexPath)
{
}

关于ios - Index.path 没有返回正确的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43638572/

相关文章:

ios - 在 xcode "Ignoring restoreCompletedTransactionsWithApplicationUsername: because already restoring transactions"的控制台中收到此消息?

ios - 我应该备份哪些证书/配置文件?

java - 如何在 kotlin 中使用 MapBuilder 并添加所有值?

带有数组的 Javascript 类无法获取长度

swift - 检测 Swift 中 NSTextField 的粘贴操作

ios - 如何更正 editor.photo Editor Delegate = self?

ios - 同步排队异步操作

php - 使用 array_udiff 比较两个对象数组

ios - ReactiveCocoa 的循环绑定(bind),如何将一个值绑定(bind)到两个输入 UI 元素

swift - 在 swift 3 中使用扩展时使用未解析的标识符