如何从其他视图控制器重命名按钮标题集(Swift 3)

时间:2018-01-21 01:22:20

标签: ios swift

我试图通过使用ViewController2中的addTarget完成功能并在ViewController1中引用一个会改变按钮标题的函数来设置ViewController1中的按钮标题。我遇到的问题是,在显示ViewController1或ViewController1上的按钮触发setButtonText()函数之前,按钮标题不会改变。如果有人可以帮助解释和解决那个很棒的问题!提前谢谢。

ViewController 1:

override func viewDidLoad() {
    super.viewDidLoad()
    buttonA.setTitle("FirstEdit", for: .normal)
    newViewController.addTarget(self, action: #selector(newVCHandler), for: .touchUpInside)
}

func newVCHandler(){
    present(ViewController2(), animated: true, completion: nil)
}

func setButtonText(){
    buttonA.setTitle("\(Title.buttonA)", for: .normal)
}

查看控制器2

override func viewDidLoad() {
    super.viewDidLoad()
    newTitleTextField.placeholder = "Set New Title"
    dismissButton.setTitle("Save and Dismiss", for: .normal)
    dismissButton.addTarget(self, action: #selector(dismissHandler), for: .touchUpInside)
}

func dismissHandler(){
    dismiss(animated: true, completion:{
    ViewController1().setButtonText()
})

2 个答案:

答案 0 :(得分:3)

Samah在评论中给了你答案。

只要您拥有ClassName()形式的代码,就会调用初始化程序并创建该类的新实例。这就像购买新车,在收音机上设置电台,丢弃新车,并想知道为什么旧车收音机上的电台没有变化。

您的第ViewController1().setButtonText()行正在创建一个不在屏幕上的新ViewController实例,并在该新实例上调用setButtonText。

您需要从View Controller 2引用另一个视图控制器(View Controller 1,就像您调用它一样)。为了帮助我们,您必须解释如何创建这些视图控制器。

答案 1 :(得分:1)

试试这个:

    //ViewController 1:

    override func viewDidLoad() {
        super.viewDidLoad()
        buttonA.setTitle("FirstEdit", for: .normal)
        newViewController.addTarget(self, action: #selector(newVCHandler), for: .touchUpInside)
    }

    func newVCHandler(){
        let vc2 = ViewController2() //Create new instance of ViewController2 and save it in variable
        vc2.refvc1 = self //save ViewController1 reference in variable
        present(vc2, animated: true, completion: nil)
    }

    func setButtonText(){
        buttonA.setTitle("\(Title.buttonA)", for: .normal)
    }

    //View Controller 2

    var refvc1: ViewController1?
    override func viewDidLoad() {
        super.viewDidLoad()
        newTitleTextField.placeholder = "Set New Title"
        dismissButton.setTitle("Save and Dismiss", for: .normal)
        dismissButton.addTarget(self, action: #selector(dismissHandler), for: .touchUpInside)
    }

    func dismissHandler(){
        dismiss(animated: true, completion:{
            self.refvc1.setButtonText()
        })