从其他视图控制器访问IBOutlet按钮

时间:2015-12-09 15:08:41

标签: ios swift

我需要访问并更改另一个视图控制器上存在的按钮的标题。这可能吗?如果是这样,我该如何做到这一点?

ViewController 1:

Class Home: UIViewController
{
   @IBOutlet  weak var testBTN: UIButton!
}

ViewController 2:

Home.testBTN // does not work I can't access the button from here

我认为我在目标C中找到了解决方案,但我不知道如何在swift中完成此任务 Access IBOutlet from another class

1 个答案:

答案 0 :(得分:1)

VC 2(发送通知):

let updateNotificationString = "com.yourcompany.yourapp.updatebutton"
NSNotificationCenter.defaultCenter().postNotificationName(updateNotificationString, object: self)

VC 1(接收和更新):

在viewDidLoad中:

let updateNotificationString = "com.yourcompany.yourapp.updatebutton"
NSNotificationCenter.defaultCenter().addObserver(self, selector: "updateButton", name: updateNotificationString, object: nil)

然后创建一个函数:

func updateButton() {
    testBTN.setTitle("New Title", forState: UIControlState.Normal)
}
相关问题