iOS StoryBoard参数传递详解

iOS 的 StoryBoard 参数传递,其实没你想得那么麻烦。大多数场景下,直接用 prepareForSegue 就够用了,简单直接,目标明确,传个值啥的分分钟搞定。你只要拿到 segue.destination,强转成对应的 VC 类型,给属性赋值就行了。逻辑清晰,出错概率低,适合绝大多数页面跳转的需求。

再稍微复杂点的场景,比如多个页面都接收消息,或者你压根不知道谁要听,那可以考虑用 广播(NotificationCenter)。发布通知时传个 userInfo,接收方监听指定的通知名,收到之后解析一下数据就能用了。挺灵活,扩展性也不错,就是代码稍微琐碎点。

下面是两个例子,一个是最常用的 prepareForSegue

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
  if segue.identifier == "YourSegueIdentifier" {
    let destinationVC = segue.destination as! YourDestinationViewController
    destinationVC.receivedData = "This the data to be passed."
  }
}

另一个是通过 NotificationCenter 广播参数:

// 发布通知
let userInfo = ["key": "your data"]
NotificationCenter.default.post(name: NSNotification.Name("YourNotificationName"), object: nil, userInfo: userInfo)

// 订阅通知 NotificationCenter.default.addObserver(self, selector: #selector(receiveNotification(_:)), name: NSNotification.Name("YourNotificationName"), object: nil)

// 接收 @objc func receiveNotification(_ notification: Notification) { if let data = notification.userInfo?["key"] as? String { print("Received data: \(data)") } }

两种方法,各有适用场景。明确目标 VC?那就用 prepareForSegue。多对多通信?NotificationCenter 挺合适。哦对了,记得通知用完要移除监听,不然容易内存泄漏。

如果你也在折腾 StoryBoard 页面跳转,传参这块建议先从 prepareForSegue 玩起,熟了之后再整广播,思路更清晰。

rar 文件大小:24.44KB