我是 swift 的新手,我只是想学习不同的技术。
情况: 我有 2 个 View Controller 。例如,1 号 View Controller 包含四个按钮(北、南、东、西)。假设您单击了北方按钮。它应该带您到 View controller number 2,并且 View controller 2 中的 UiLabel 应该显示按下的任何按钮的名称(在本例中为“North”)。 我知道当你向前传递信息时,你应该使用“准备转场”方法,但是有没有办法用所有 4 个按钮来做到这一点?我在 View Controller 2 中还有一个可选的字符串变量,它应该捕获从 View Controller 1 传递的信息。我到处搜索但我还没有得到答案。
我目前在 View Controller 1 中的代码:
@IBAction func north(sender: UIButton) {
}
@IBAction func east(sender: UIButton) {
}
@IBAction func west(sender: UIButton) {
}
@IBAction func south(sender: UIButton) {
}
我目前在 View Controller 2 中的代码:
@IBoutlet weak var label2: UILabel!
var updateTheLabel: String?
override func viewDidLoad() {
super.viewDidLoad()
label2.text = updateTheLabel!
}
问题: 我如何使用所有四个按钮执行 segue 以转到第二个 View Controller 并分别更新 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
中,让我们假设这两个 View Controller 通过带有标识符 secondControllerSegue
的 segue 连接。
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "secondControllerSegue" {
let controller = segue.destinationViewController as! SecondViewController
controller.updateTheLabel = buttonText
}
}
这会将我们之前捕获的 buttonText
发送到 secondViewController
关于ios - 如何快速将信息传递给第二个 View Controller 中的 Uilabel?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37759193/