2017-05-29 30 views
0

我想分配一個變量到一個按鈕,並調用該變量將其傳遞給另一個viewcontroller。如何分配和從一個按鈕調用變量

目前我發送按鈕的標題是這樣的:

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

但我有一個按鈕,我想一個字符串發送到另一個視圖 - 控制是從它的標題不同。我試圖在身份檢查員的「標籤」位置添加一些東西,但似乎並不是正確的做法。

任何意見表示讚賞,謝謝!

+0

你可以從你在哪裏傳遞文本到母親的ViewController – suhit

+0

我的問題都在從一個發送信息方面增加更多的代碼或功能viewcontroller到另一個,我只需要知道如何分配一個值/標籤/變量/任何東西到按鈕,所以我可以調用它發送。我的代碼當前發送按鈕的標題,我只想知道如何發送其他東西。 – tfcamp

+0

「如何分配一個值/標籤/變量/任何東西到按鈕」部分有點不清楚,你想傳遞字符串到下一個視圖控制器,以便您可以設置按鈕的文本? – suhit

回答

1

首先在明年的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

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

,或者你可以用標識爲您的子類instantiet的viewController VC並以相同的方式傳遞值

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

如有任何疑問,請:)祝快樂編碼

相關問題