我是swift的新手,我只是想学习不同的技术。
情况:我有两个视图控制器。例如,1号视图控制器由四个按钮(北、南、东、西)组成。比方说你点击北方按钮。它将带您进入View controller number 2,View controller 2中的UiLabel应显示按下的任何按钮的名称(在这种情况下为"North")。我知道,当你向前传递信息时,你应该使用"prepare for segue"方法,但有没有办法用所有4个按钮做到这一点?我在视图控制器2中还有一个可选的字符串变量,它应该捕获从视图控制器1传递的信息。我到处找了,但还没有得到答案。
我目前看到的代码控制器1:
@IBAction func north(sender: UIButton) {
}
@IBAction func east(sender: UIButton) {
}
@IBAction func west(sender: UIButton) {
}
@IBAction func south(sender: UIButton) {
}
我目前在视图控制器2中的代码2:
@IBoutlet weak var label2: UILabel!
var updateTheLabel: String?
override func viewDidLoad() {
super.viewDidLoad()
label2.text = updateTheLabel!
}
问题:如何使用所有四个按钮执行segue以转到第二视图控制器并分别更新UiLabel?
添加到@ahmad farrag的解决方案
您可以修改IB操作以从按下的按钮中拾取文本
var buttonText = ""
@IBAction func north(sender: UIButton) {
buttonText = sender.currentTitle.text
}
@IBAction func east(sender: UIButton) {
buttonText = sender.currentTitle.text
}
@IBAction func west(sender: UIButton) {
buttonText = sender.currentTitle.text
}
@IBAction func south(sender: UIButton) {
buttonText = sender.currentTitle.text
}
这将把按钮中的文本分配给buttonText
变量。现在,在您的prepareForSegue
中,让我们假设这两个视图控制器由一个标识符为secondControllerSegue
的segue连接。
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "secondControllerSegue" {
let controller = segue.destinationViewController as! SecondViewController
controller.updateTheLabel = buttonText
}
}
这将把我们之前捕获的buttonText
发送到secondViewController
可以。
只需从故事板中删除片段,然后以编程方式执行此操作,并将updateTheLabel属性公开。
例如:
let secondViewController = self.storyboard?.instantiateViewControllerWithIdentifier("SecondViewControllerIdentifier") as? SecondViewController
secondViewController.updateTheLabel = "Whatever you like"
//Then push or present to the secondViewController depending on your hierarchy.
//self.navigationController?.pushViewController(secondViewController!, animated: true)
//or
//self.presentViewController(secondViewController!, animated: true, completion: nil)
您可以使用NSNotificationion Centre在ViewController 中
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(ViewController.testObserver(_:)), name: "testObserver", object: ios)
目的地视图控制器
func testObserver(noti : NSNotification){
title = noti.object as? String
}