swift UISplitViewController检测到按下返回按钮

rqenqsqc  于 2023-03-28  发布在  Swift
关注(0)|答案(3)|浏览(172)

我有一个UISplitViewController,我想始终显示iPad的主视图控制器和细节视图控制器。这一行为我处理了这个问题:

// Always display master and detail in large screens
self.preferredDisplayMode = UISplitViewControllerDisplayMode.AllVisible

在prepareForSegue中,当打开细节视图控制器时,我有以下几行代码用于Back按钮

controller.navigationItem.leftBarButtonItem = self.splitViewController?.displayModeButtonItem()
controller.navigationItem.leftItemsSupplementBackButton = true

现在,当用户按下返回按钮时,我将在Master视图控制器隐藏后执行一个操作。我没有找到如何做到这一点的任何运气。在SplitViewControllerDelegate中,我尝试用途:

func splitViewController(svc: UISplitViewController, willChangeToDisplayMode displayMode: UISplitViewControllerDisplayMode)

但是这个函数是在Detail视图控制器变成全屏之前被调用的。有没有一个函数或其他东西可以帮助我在UISplitViewController完成隐藏Master视图时通知我?

ctehm74n

ctehm74n1#

您可以在DetailViewController中的视图上添加观察者,并在触发时执行特定操作:

- (void)viewDidLoad {
  [super viewDidLoad];

  [self addObserver:self forKeyPath:@"view.frame" options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionInitial context:nil];
}

- (void)viewWillDisappear:(BOOL)animated {
  [super viewWillDisappear:animated];
  if ([self observationInfo]) {
    @try {
      [self removeObserver:self forKeyPath:@"view.frame"];
    }
    @catch (NSException *exception) {}

  }
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
  if (object == self && [keyPath isEqualToString:@"view.frame"]) {
    // do your action here
  }
}
zbsbpyhn

zbsbpyhn2#

你可以试试delegate方法

- (UISplitViewControllerDisplayMode)targetDisplayModeForActionInSplitViewController:(UISplitViewController *)svc;
c7rzv4ha

c7rzv4ha3#

我从here那里得到了答案,需要放到主控制器**中(左边的那个)。
仅供参考,这使扩展按钮失效,为了使其扩展/收缩,我将额外的代码放入doSomethingWhenExpandButtonTapped()

navigationController?.topViewController?.navigationItem.leftBarButtonItem?.action = #selector(doSomethingWhenExpandButtonTapped)
navigationController?.topViewController?.navigationItem.leftBarButtonItem?.target = self

@objc func doSomethingWhenExpandButtonTapped() {
    print("splitViewController's expand and back button pressed")

    if splitViewController?.preferredDisplayMode == .allVisible {
        splitViewController?.preferredDisplayMode = .primaryHidden
    } else {
        splitViewController?.preferredDisplayMode = .allVisible
    }
}

相关问题