【问题标题】:How to assign and call a variable to/from a button如何为按钮分配和调用变量
【发布时间】:2017-10-29 22:35:14
【问题描述】:

我正在尝试将变量分配给按钮并调用该变量以将其传递给另一个视图控制器。

目前我正在发送这样的按钮标题:

((sender as! UIButton).titleLabel?.text)!

但是我有一个按钮,我想将一个字符串发送到另一个与其标题不同的视图控制器。我尝试在身份检查器的“标签”位置添加一些东西,但这似乎不是正确的方法。

感谢任何建议,谢谢!

【问题讨论】:

  • 您能否添加更多代码或函数,从您将文本传递到母视图控制器的位置
  • 我已经准备好将信息从一个视图控制器发送到另一个视图控制器,我只需要知道如何为按钮分配值/标签/变量/任何内容,以便我可以调用它发送。我的代码当前发送按钮的标题,我只想知道如何发送其他内容。
  • “如何为按钮分配值/标签/变量/任何内容”部分有点不清楚,您是否要将字符串传递给下一个视图控制器以便您可以设置按钮的文本?
  • 是的,我想将一个字符串传递给下一个视图控制器以设置该视图控制器上按钮的文本。

标签: ios swift variables button viewcontroller


【解决方案1】:

将变量存储在类中的其他位置并像这样设置 didSet 注释

var myTitle: String{
didSet{
self.theDesiredButton.setTitle(myTitle, for: .normal)
//alternatively you can use 
self.theDesiredButton.title = myTitle
     }

}

这里将变量传递给另一个控制器:

override func prepareForSegue(/*dunno args I code from mobile*/){
//guess figure out segueIdentifier and desired Vc subclass
if let myCustomVC = segue.viewContoller as? CustomVCSubclass{
myCustomVC.valueToPass = self.myTitle
}
}

或者您可以将带有标识符的 viewController 实例化为您的子类 VC,并以相同的方式传递值

func pushNextVC(){
if let newVC = storyboard.instantiateViewController(with: "identifierFromIB") as? CustomVCSubclass{
newVC.valueToPass = self.myTitle
self.NavigationController.push(newVC)
}
 }

如有任何问题,请询问:) 祝编码愉快

【讨论】:

    【解决方案2】:

    首先在下一个 ViewController 中为按钮创建一个 outlet,并添加一个字符串变量并使用 viewDidLoad 中的 setTitle(_ title: String?, for state: UIControlState) 方法设置标题

    class SecondViewController: UIViewController {
    
        @IBOutlet weak var button: UIButton!
        var buttonText: String?
    
        override func viewDidLoad() {
            super.viewDidLoad()
    
            if let buttonText = buttonText {
                button.setTitle(buttonText, for: .normal)
            }
        }
    }
    

    并在 FirstViewController 中将文本分配给 SecondVC 中的字符串变量,如下所示

    class FirstViewController: UIViewController {
    
        override func viewDidLoad() {
            super.viewDidLoad()
    
            // Do any additional setup after loading the view.
        }
    
        @IBAction func buttonClicked(_ sender: UIButton) {
            self.performSegue(withIdentifier: "CustomSegue", sender: self)
        }
    
        override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
            if segue.identifier == "CustomSegue" {
                let vc = segue.destination as? SecondViewController
                vc?.buttonText = "ButtonTitle"
            }
        }
    }
    

    【讨论】:

    • 为了传递按钮标题,您可以将 sender 作为一种 UIButton 而不是 Any 以便您可以使用 sender.titleLabel?.text 发送 buttonTitle
    猜你喜欢
    • 2019-08-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-18
    • 1970-01-01
    相关资源
    最近更新 更多