如何分配和从一个按钮调用变量

问题描述:

我想分配一个变量到一个按钮,并调用该变量将其传递给另一个viewcontroller。如何分配和从一个按钮调用变量

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

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

但我有一个按钮,我想一个字符串发送到另一个视图 - 控制是从它的标题不同。我试图在身份检查员的“标签”位置添加一些东西,但似乎并不是正确的做法。

任何意见表示赞赏,谢谢!

+0

你可以从你在哪里传递文本到母亲的ViewController – suhit

+0

我的问题都在从一个发送信息方面增加更多的代码或功能viewcontroller到另一个,我只需要知道如何分配一个值/标签/变量/任何东西到按钮,所以我可以调用它发送。我的代码当前发送按钮的标题,我只想知道如何发送其他东西。 – tfcamp

+0

“如何分配一个值/标签/变量/任何东西到按钮”部分有点不清楚,你想传递字符串到下一个视图控制器,以便您可以设置按钮的文本? – suhit

首先在明年的ViewController创建出口到按钮,还可以添加一个字符串变量和使用该方法setTitle(_ title: String?, for state: UIControlState)在viewDidLoad中

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" 
     } 
    } 
} 
+0

用于传递按钮标题,您可以将发件人作为UIButton类型而不是Any,以便您可以使用sender.titleLabel?.text发送buttonTitle – suhit

存储变量的类的其他地方,并设置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 
} 
} 

,或者你可以用标识为您的子类instantiet的viewController VC并以相同的方式传递值

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

如有任何疑问,请:)祝快乐编码