How to pass button title to next view controller in Swift

…衆ロ難τιáo~ 提交于 2021-02-10 20:24:40

问题


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)
    }

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
}

The commented lines were failed attempts.

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.


回答1:


In your button function, pass the button along as the sender of the segue:

func collegeSelected(sender: UIButton!) {
    self.performSegueWithIdentifier("goToTableView", sender: sender)
}

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
    }
}


来源:https://stackoverflow.com/questions/28519105/how-to-pass-button-title-to-next-view-controller-in-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!