如何将按钮标题传递给 Swift 中的下一个视图控制器 [英] How to pass button title to next view controller in Swift
问题描述
我在 viewDidLoad 的循环中定义了几个按钮.它们位于滚动视图中的内容视图中.
I have several buttons defined in a loop in viewDidLoad. They are inside a content view, which is in a scroll view.
for var i:Int = 0; i < colleges.count; i++ {
let collegeButton = UIButton.buttonWithType(UIButtonType.System) as UIButton
collegeButton.frame = CGRectMake(0, 0, self.contentView.frame.size.width, 30)
collegeButton.center = CGPoint(x: self.contentView.center.x, y: 30 * CGFloat(i) + 30)
collegeButton.setTitle(sortedColleges[i], forState: UIControlState.Normal)
collegeButton.setTitleColor(UIColor.darkGrayColor(), forState: UIControlState.Normal)
collegeButton.titleLabel?.font = UIFont(name: "Hiragino Kaku Gothic ProN", size: 15)
collegeButton.addTarget(self, action: "collegeSelected:", forControlEvents: UIControlEvents.TouchUpInside)
self.contentView.addSubview(collegeButton)
}
如您所见,每个按钮的标题都是根据先前定义的字符串数组设置的.Whenever a button is selected, a segue is called to move to a table view, which is embedded in a navigation controller.
As you can see, the title of each button is set based on a previously defined array of strings. Whenever a button is selected, a segue is called to move to a table view, which is embedded in a navigation controller.
我需要将导航控制器标题设置为与特定按钮标题相同.
I need to set the navigation controller title to be the same as the specific button title.
以下是我尝试过的一些方法:
Here are some things I have tried:
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
var destViewController:videosTableView = segue.destinationViewController as videosTableView
//destViewController.title = collegeButton.titleLabel?.text
//var buttonTitle = sender.titleLabel?.text
//destViewController.title = buttonTitle
}
注释行是失败的尝试.
我还尝试在按下按钮时调用的动作函数中工作:
I also tried working in the action function called when the button is pressed:
func collegeSelected(sender: UIButton!) {
self.performSegueWithIdentifier("goToTableView", sender: self)
//Set navigation title of next screen to title of button
var buttonTitle = sender.titleLabel?.text
println(buttonTitle)
}
使用发件人获取按钮标题有效,但我不知道如何将其传递给下一个视图控制器.
Using the sender to get the button title works, but I don't know how to pass it to the next view controller.
非常感谢任何可以提供帮助的人.
Thanks a lot to anyone who can help.
推荐答案
在按钮函数中,将按钮作为 segue 的发送者传递:
In your button function, pass the button along as the sender of the segue:
func collegeSelected(sender: UIButton!) {
self.performSegueWithIdentifier("goToTableView", sender: sender)
}
然后在prepareForSegue
中,从发送者(即按钮)获取按钮标题:
Then in prepareForSegue
, get the button title from the sender (i.e. the button):
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
let destViewController = segue.destinationViewController as videosTableView
if let buttonTitle = (sender as? UIButton)?.titleLabel?.text {
destViewController.title = buttonTitle
}
}
这篇关于如何将按钮标题传递给 Swift 中的下一个视图控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!