我试图将一个变量分配给一个按钮并调用该变量将其传递给另一个viewcontroller。
目前我发送的按钮标题如下:
((sender as! UIButton).titleLabel?.text)!
但我有一个按钮,我想将一个字符串发送到另一个与其标题不同的viewcontroller。我尝试在"标签中添加一些东西"在身份检查员中找到,但它似乎不是正确的方法。
感谢任何建议,谢谢!
答案 0 :(得分: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
}
}
或者你可以使用标识符作为你的子类VC的instantiet viewController并以同样的方式传递值
func pushNextVC(){
if let newVC = storyboard.instantiateViewController(with: "identifierFromIB") as? CustomVCSubclass{
newVC.valueToPass = self.myTitle
self.NavigationController.push(newVC)
}
}
如有任何问题请教:)祝快乐编码
答案 1 :(得分:1)
首先在下一个ViewController中为按钮创建一个插座,并添加一个字符串变量,并使用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"
}
}
}