新手迅速,希望我能得到答案。当按下按钮时,我需要将NSArray传递给下一个视图控制器并按随机顺序传递。我有UILabel和在第二个视图控制器中声明的一个变量,segue似乎正在工作。只有peoblem它没有传递任何价值。这是我的代码。
@IBAction func ressedbutton(_ sender: Any) {
let quotes: NSArray = ["Quote 000", "Quote 001", "Quote 002"]
let range: UInt32 = UInt32(quotes.count)
let randomNumber = Int(arc4random_uniform(range))
let QuoteString = quotes.object(at: randomNumber)
// self.resul.text = QuoteString as? String
performSegue(withIdentifier: "showresult", sender: QuoteString)
let myVC = storyboard?.instantiateViewController(withIdentifier: "result") as! result
myVC.stringPassed =
(QuoteString as? String)!
}
和第二个视图的代码是
类结果:UIViewController {
var stringPassed = ""
@IBOutlet weak var ResultLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
ResultLabel.text = stringPassed
我认为我的问题出在myvc.stringpassed = ...?如何通过随机传递arry?
先谢谢。
答案 0 :(得分:1)
您需要做的是在sender
中使用performSegue
传递该值,然后在prepare(for:sender:)
中访问该值并将值传递给destinationController。
performSegue(withIdentifier: "showresult", sender: QuoteString)
现在在sender
prepare(for:sender:)
参数
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let vc = segue.destination as? result, let data = sender as? String {
vc.stringPassed = data
}
}
答案 1 :(得分:0)
您必须使用prepare(for segue:UIStoryboardSegue,sender:Any?)方法将数据分配给toViewController.UIStoryboardSegue对象segue具有标识符,目标和源等属性。
在此方法中,首先检查标识符,如果匹配,则将目标控制器强制转换为自定义视图控制器,并将数据分配给视图控制器对象。
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "showresult"{
if let toViewController = segue.destination as? result {
vc.stringPassed = QuoteString
}
}
}
答案 2 :(得分:0)
尝试这种方式删除segue将Storyboard ID提供给您想要传递数据并在下面粘贴相同Storyboard Id的视图控制器(YourIdentifier)
@IBAction func ressedbutton(_ sender: Any) {
let quotes: NSArray = ["Quote 000", "Quote 001", "Quote 002"]
let range: UInt32 = UInt32(quotes.count)
let randomNumber = Int(arc4random_uniform(range))
let QuoteString = quotes.object(at: randomNumber)
// self.resul.text = QuoteString as? String
let vc = storyboard?.instantiateViewController(withIdentifier:"YourIdentifier") as! YourNextViewController
vc.stringPassed = (QuoteString as? String)!
self.present(vc, animated: true, completion: nil)
}