有两种方式:
1) 使用委托协议(推荐)
a) 在您的孩子中,创建一个委托协议,并在将持有委托的子 VC 上创建一个可选属性。
protocol ChildViewControllerDelegate {
}
class ChildViewController: UIViewController {
var delegate:ChildViewControllerDelegate?
}
b) 在委托协议中创建一个在按钮被按下时将被调用的方法,并在委托上调用该方法的子进程中实现buttonWasPressed() 方法。 (您需要将此方法与情节提要中的按钮连接起来)
protocol ChildViewControllerDelegate {
func childViewControllerDidPressButton(childViewController:ChildViewController)
}
class ChildViewController: UIViewController {
var delegate:ChildViewControllerDelegate?
@IBOutlet weak var button: UIButton!
@IBAction func buttonWasPressed(sender: AnyObject) {
self.delegate?.childViewControllerDidPressButton(self)
}
}
c) 让你的父视图控制器符合子协议
class ParentViewController: UIViewController, ChildViewControllerDelegate {
func childViewControllerDidPressButton(childViewController: ChildViewController) {
// Do fun handling of child button presses!
}
}
c) 当子进程嵌入到父进程中时,会运行一种特殊的 segue,称为 embed segue。您可以在情节提要中看到它——它是连接孩子和父母的线:
在情节提要中为该 segue 添加一个标识符:
并在父视图控制器中为其设置一个常量:
struct Constants {
static let embedSegue = "embedSegue"
}
class ParentViewController: UIViewController, ChildViewControllerDelegate {
func childViewControllerDidPressButton(childViewController: ChildViewController) {
// Do fun handling of child button presses!
}
}
d) 然后在父视图控制器中,覆盖 prepareForSegue() 方法并检查 segue.identifier 是否与您设置的标识符匹配。如果是这样,那么您可以通过segue.destinationViewController 获得对子视图控制器的引用。将此作为您的子视图控制器,然后您可以将父视图控制器设置为它的委托:
struct Constants {
static let embedSegue = "embedSegue"
}
class ParentViewController: UIViewController, ChildViewControllerDelegate {
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == Constants.embedSegue {
let childViewController = segue.destinationViewController as ChildViewController
childViewController.delegate = self
}
}
func childViewControllerDidPressButton(childViewController: ChildViewController) {
// Do fun handling of child button presses!
}
}
e) 赢了!
2) 使用 NSNotification 和 NSNotificationCenter
您可以将这些视为类似于 ActionScript 事件,但它们不会像 AS 那样自动通过视图层次结构冒泡。相反,通知是通过NSNotificationCenter 全局发送的。我更喜欢只在有多个对象需要监听一个特定事件时才使用它。
您可以在此处找到有关NSNotification 和NSNotificationCenter 的更多信息:https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSNotificationCenter_Class/