我正在UIViewController中定义此对象,并尝试在其他视图控制器中访问myIndex。我该怎么办?
我想以编程方式在没有情节提要的情况下执行此操作。任何帮助深表感谢!
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
//NSLog("You selected cell number: \(indexPath.row)!")
let myIndex = indexPath.row
}
答案 0 :(得分:1)
您必须考虑像这样传递Indexpath:
performSegue(withIdentifier: "NextView", sender: indexPath)
func prepareForSegue(segue: UIStoryboardSegue, sender: Any) {
let indexPath = sender as! IndexPath
let eventStruct = post[indexPath.row]
let secondViewController = segue.destination as? NextViewController
secondViewController?.data = sender as AnyObject
}
答案 1 :(得分:0)
如果要从项目的任何位置访问,可以将数据存储在userdefault中。在didSelectRowAt内部,使用键myIndex设置indexPath.row,该键应该是唯一的:
UserDefaults.standard.set(indexPath.row, forKey: "myIndex")
然后从任何viewController检索数据:
If UserDefaults.standard.object(forKey: "myIndex")!=nil{
let savedIndexPath = UserDefaults.standard.integer(forKey: "myIndex")
}