bax*_*axu 2 uiviewcontroller ios segue swift
使用此代码,我可以"segue"到我的视图控制器的同一个实例
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let vc = storyboard.instantiateViewController(withIdentifier: "DetailVC")
self.navigationController?.pushViewController(vc, animated: true)
}
Run Code Online (Sandbox Code Playgroud)
但是,如何传递数据?我只知道如何使用segue选项传递数据.当我用这个运行代码时,我得到nil错误,因为新的实例化视图控制器无法读取数据.
例如我在这里添加,有关详细说明,您可以从此处获取教程
class SecondViewController: UIViewController {
var myStringValue:String?
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
// We will simply print out the value here
print("The value of myStringValue is: \(myStringValue!)")
}
Run Code Online (Sandbox Code Playgroud)
并将字符串发送为
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let vc = storyboard.instantiateViewController(withIdentifier: "DetailVC") as! SecondViewController
vc.myStringValue = "yourvalue"
self.navigationController?.pushViewController(vc, animated: true)
}
Run Code Online (Sandbox Code Playgroud)
首先.这不是一个segue.这只是将另一个视图推向堆栈.并且(如Ashley Mills所说)这与您当前所处的实例不同.这是一个视图控制器的新实例.
但您需要做的就是填充数据.你已经在这里安装了控制器......
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let storyboard = UIStoryboard(name: "Main", bundle: nil)
// you need to cast this next line to the type of VC.
let vc = storyboard.instantiateViewController(withIdentifier: "DetailVC") as! DetailVC // or whatever it is
// vc is the controller. Just put the properties in it.
vc.thePropertyYouWantToSet = theValue
self.navigationController?.pushViewController(vc, animated: true)
}
Run Code Online (Sandbox Code Playgroud)
你使用的不是转场。这只是将视图控制器的一个新实例(不是同一个)推送到导航堆栈上。
继续,在您的故事板中,您只需将链接从集合视图单元格拖到视图控制器,然后在prepareForSegue方法中分配数据......
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if let viewController = segue.destinationViewController as? DetailVC {
viewController.someProperty = self.someProperty
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6616 次 |
| 最近记录: |