Swift4中嵌入导航控制器的UIPageViewController更新子控制器UI方法
最简单的实现方式推荐
嘿,针对你这个需求,有几种简洁的实现思路,我给你列两个最容易上手的:
方法一:用通知中心(NotificationCenter)—— 零耦合,快速实现
这应该是最省心的方式,不需要定义额外的协议或者代理,直接通过通知传递编辑状态:
- 在你的
UIPageViewController中重写编辑状态改变的方法,发送通知:
override func setEditing(_ editing: Bool, animated: Bool) { super.setEditing(editing, animated: animated) // 发送通知,把当前编辑状态传出去 NotificationCenter.default.post( name: NSNotification.Name("EditStateDidChange"), object: editing ) }
- 在每个子ViewController中监听这个通知,更新UI:
override func viewDidLoad() { super.viewDidLoad() // 注册通知监听 NotificationCenter.default.addObserver( self, selector: #selector(handleEditStateUpdate(_:)), name: NSNotification.Name("EditStateDidChange"), object: nil ) } @objc private func handleEditStateUpdate(_ notification: Notification) { guard let isEditing = notification.object as? Bool else { return } // 这里写你的UI更新逻辑,比如隐藏操作按钮、改变文本样式等 if isEditing { // 编辑状态下的UI变化 editButton.isHidden = false titleLabel.textColor = .systemRed } else { // 非编辑状态下的UI变化 editButton.isHidden = true titleLabel.textColor = .label } } // 记得在销毁时移除监听,避免内存泄漏 deinit { NotificationCenter.default.removeObserver(self) }
方法二:直接调用子VC的方法—— 类型明确时更高效
如果你的所有子ViewController都是同一个类(或者遵守同一个协议),直接获取当前显示的子VC并调用指定方法会更直接:
- 先定义一个协议,约定子VC需要实现的UI更新方法:
protocol EditStateUpdatable: UIViewController { func updateUI(forEditingState isEditing: Bool) }
- 让你的子ViewController遵守这个协议并实现方法:
class YourChildVC: UIViewController, EditStateUpdatable { func updateUI(forEditingState isEditing: Bool) { // 这里写UI更新逻辑 collectionView.allowsSelection = !isEditing deleteButton.isHidden = !isEditing } }
- 在
UIPageViewController的编辑状态改变方法中,获取当前子VC并调用方法:
override func setEditing(_ editing: Bool, animated: Bool) { super.setEditing(editing, animated: animated) // 获取当前显示的第一个子VC,强转成协议类型 if let currentChildVC = viewControllers?.first as? EditStateUpdatable { currentChildVC.updateUI(forEditingState: editing) } }
选哪个?
- 如果子VC类型不统一、或者不想耦合,优先选通知中心,实现最快;
- 如果所有子VC都是同一类型,选直接调用方法,代码更清晰,也不需要处理通知的注册/移除。
内容的提问来源于stack exchange,提问作者guiaume
相关产品推荐
相关产品推荐

