如何在自定义函数中达到indexPath ?



我试图在第一个UIAlertController中选择一个选项时打开第二个UIAlertController,但我无法达到indexPath,以便从第二个AlertController的textField设置属性。下面是代码片段:

override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {

let ac = UIAlertController(title: "Choose an action", message: nil, preferredStyle: .alert)
ac.addAction(UIAlertAction(title: "Rename a person", style: .default, handler: alert2))
ac.addAction(UIAlertAction(title: "Delete", style: .destructive) {
[weak self] _ in
self?.people.remove(at: indexPath.item)
self?.collectionView.reloadData()
})
ac.addAction(UIAlertAction(title: "Cancel", style: .cancel))
present(ac, animated: true)
}
func alert2(alert: UIAlertAction!) {
let ac2 = UIAlertController(title: "Type in a name", message: nil, preferredStyle: .alert)
ac2.addAction(UIAlertAction(title: "Ok", style: .default, handler: nil))
self.present(ac2, animated: true)
guard let newName = ac2.textFields?[0].text else { return }
let person = people[indexPath.item]
person.name = newName
self.collectionView.reloadData()
ac2.addTextField()
}

我也得到了"无法找到'indexPath'在作用域"这个字符串中的错误:let person = people[indexPath.item]你能帮我算一下吗?

需要将indexPath传递给alert2函数。试试这个新的alert2函数:

func alert2(alert: UIAlertAction!, indexPath:IndexPath) {
let ac2 = UIAlertController(title: "Type in a name", message: nil, preferredStyle: .alert)
ac2.addAction(UIAlertAction(title: "Ok", style: .default, handler: nil))
self.present(ac2, animated: true)
guard let newName = ac2.textFields?[0].text else { return }
let person = people[indexPath.item]
person.name = newName
self.collectionView.reloadData()
ac2.addTextField()
}

你将替换这一行:

ac.addAction(UIAlertAction(title: "Rename a person", style: .default, handler: alert2))

与这个:

let action = UIAlertAction(title: "Rename a person", style: .default) { action in
alert2(alert: action, indexPath: indexPath)
}
ac.addAction(action)

无法在给定的作用域中找到'indexPath',因为您的函数无法找到索引号。您应该通过函数alert2传递Indexpath参数将函数func alert2(alert: UIAlertAction!)更改为func alert2(alert: UIAlertAction!, indexPath:IndexPath),然后您将找到索引。参考:

func alert2(alert: UIAlertAction!, indexPath:IndexPath) {
... your code ...
let person = people[indexPath.item]
... your code ...
}

最新更新