IT박스

iOS에서 "뒤로"탐색 단추 동작 처리 시도

itboxs 2020. 10. 31. 09:28
반응형

iOS에서 "뒤로"탐색 단추 동작 처리 시도


사용자가 탐색 표시 줄의 "뒤로"버튼을 누를 때이를 감지해야 몇 가지 작업을 수행 할 수 있습니다. 다음과 같이 이러한 버튼에 대한 작업을 수동으로 설정하려고합니다.

[self.navigationItem.backBarButtonItem setAction:@selector(performBackNavigation:)];

- (void)performBackNavigation:(id)sender
{
   // Do operations

   [self.navigationController popViewControllerAnimated:NO];
}

나는 처음에 그 코드를 뷰 컨트롤러 자체에 배치했지만 그것이 인 self.navigationItem.backBarButtonItem것처럼 보였으 nil므로 동일한 코드를 상위 뷰 컨트롤러로 옮겼습니다. 그러나 나는 그것을 작동시킬 수 없습니다. 이 문제에 관한 게시물을 몇 개 읽었으며 일부는 선택기를 상위 뷰 컨트롤러에서 설정해야한다고 말했지만 어쨌든 작동하지 않습니다 ... 내가 뭘 잘못하고 있니?

감사


VIewWillDisappearNavigationItem의 뒤로 버튼 누름을 감지하는 방법을 사용하여 다음 코드를 시도하십시오 .

-(void) viewWillDisappear:(BOOL)animated
{
    if ([self.navigationController.viewControllers indexOfObject:self]==NSNotFound) 
    {
        // Navigation button was pressed. Do some stuff 
        [self.navigationController popViewControllerAnimated:NO];
    }
    [super viewWillDisappear:animated];
}

또는 탐색 모음 버튼의 동작을 얻는 또 다른 방법이 있습니다.

뒤로 버튼의 UINavigationItem에 대한 사용자 정의 버튼을 만듭니다.

예 :

ViewDidLoad에서 :

- (void)viewDidLoad 
{
    [super viewDidLoad];
    UIBarButtonItem *newBackButton = [[UIBarButtonItem alloc] initWithTitle:@"Home" style:UIBarButtonItemStyleBordered target:self action:@selector(home:)];
    self.navigationItem.leftBarButtonItem=newBackButton;
}

-(void)home:(UIBarButtonItem *)sender 
{
    [self.navigationController popToRootViewControllerAnimated:YES];
}

빠른 :

override func willMoveToParentViewController(parent: UIViewController?) 
{
    if parent == nil 
    {
        // Back btn Event handler
    }
}

빠른

override func didMoveToParentViewController(parent: UIViewController?) {
    if parent == nil {
        //"Back pressed"
    }
}

아마도이 답변은 귀하의 설명이 아니라 질문 제목에 맞을 것입니다. 에서 뒤로 버튼을 탭한시기를 알고 싶을 때 유용합니다 UINavigationBar.

이 경우 UINavigationBarDelegate프로토콜 을 사용 하고 다음 방법 중 하나를 구현할 수 있습니다 .

- (BOOL)navigationBar:(UINavigationBar *)navigationBar shouldPopItem:(UINavigationItem *)item;
- (void)navigationBar:(UINavigationBar *)navigationBar didPopItem:(UINavigationItem *)item;

didPopItem메서드가 호출 되면 뒤로 버튼을 누르거나 [UINavigationBar popNavigationItemAnimated:]메서드 를 사용 하고 탐색 모음이 항목을 팝 했기 때문 입니다.

이제 어떤 작업이 didPopItem메소드를 트리거했는지 알고 싶다면 플래그를 사용할 수 있습니다.

이 접근 방식을 사용하면 iOS 뒤로 버튼과 비슷하게 만들기 위해 화살표 이미지가있는 왼쪽 막대 버튼 항목을 수동으로 추가 할 필요가 없으며 내 사용자 지정 대상 / 동작을 설정할 수 있습니다.


예를 보겠습니다.

페이지보기 컨트롤러와 사용자 지정 페이지 표시기보기가있는보기 컨트롤러가 있습니다. 또한 사용자 지정 UINavigationBar를 사용하여 내가 어떤 페이지인지 알 수있는 제목을 표시하고 이전 페이지로 돌아가는 뒤로 단추를 사용하고 있습니다. 또한 페이지 컨트롤러에서 이전 / 다음 페이지로 스 와이프 할 수도 있습니다.

#pragma mark - UIPageViewController Delegate Methods
- (void)pageViewController:(UIPageViewController *)pageViewController didFinishAnimating:(BOOL)finished previousViewControllers:(NSArray *)previousViewControllers transitionCompleted:(BOOL)completed {

    if( completed ) {

        //...

        if( currentIndex > lastIndex ) {

            UINavigationItem *navigationItem = [[UINavigationItem alloc] initWithTitle:@"Some page title"];

            [[_someViewController navigationBar] pushNavigationItem:navigationItem animated:YES];
            [[_someViewController pageControl] setCurrentPage:currentIndex];
        } else {
            _autoPop = YES; //We pop the item automatically from code.
            [[_someViewController navigationBar] popNavigationItemAnimated:YES];
            [[_someViewController pageControl] setCurrentPage:currentIndex];
        }
    }

}

그런 다음 UINavigationBar 대리자 메서드를 구현합니다.

#pragma mark - UINavigationBar Delegate Methods
- (BOOL)navigationBar:(UINavigationBar *)navigationBar shouldPopItem:(UINavigationItem *)item {
    if( !_autoPop ) {
        //Pop by back button tap
    } else {
        //Pop from code
    }

    _autoPop = NO;

    return YES;
}

이 경우 shouldPopItem에는 팝이 애니메이션화되어 사용하고 전환이 완료 될 때까지 기다리지 않고 뒤로 버튼을 즉시 처리하고 싶었습니다.


The problem with didMoveToParentViewController it's that it gets called once the parent view is fully visible again so if you need to perform some tasks before that, it won't work.

And it doesn't work with the driven animation gesture. Using willMoveToParentViewController works better.

Objective-c

- (void)willMoveToParentViewController:(UIViewController *)parent{
    if (parent == NULL) {
        // ...
    }
}

Swift

override func willMoveToParentViewController(parent: UIViewController?) {
    if parent == nil {
        // ...  
    }
}

This is Objective-C version of dadachi's Answer :

Objective-C

- (void)didMoveToParentViewController:(UIViewController *)parent{
    if (parent == NULL) {
        NSLog(@"Back Pressed");
    }
}

Set the UINavigationBar's delegate, and then use:

- (BOOL)navigationBar:(UINavigationBar *)navigationBar shouldPopItem:(UINavigationItem *)item {
    //handle the action here
}

Set the UINavigationControllerDelegate and implement this delegate func (Swift):

func navigationController(navigationController: UINavigationController, willShowViewController viewController: UIViewController, animated: Bool) {
    if viewController is <target class> {
        //if the only way to get back - back button was pressed
    }
}

None of the other solutions worked for me, but this does:

Create your own subclass of UINavigationController, make it implement the UINavigationBarDelegate (no need to manually set the navigation bar's delegate), add a UIViewController extension that defines a method to be called on a back button press, and then implement this method in your UINavigationController subclass:

func navigationBar(_ navigationBar: UINavigationBar, shouldPop item: UINavigationItem) -> Bool {
    self.topViewController?.methodToBeCalledOnBackButtonPress()
    self.popViewController(animated: true)
    return true
}

Use a custom UINavigationController subclass, which implements the shouldPop method.

In Swift:

class NavigationController: UINavigationController, UINavigationBarDelegate
{
    var shouldPopHandler: (() -> Bool)?

    func navigationBar(_ navigationBar: UINavigationBar, shouldPop item: UINavigationItem) -> Bool
    {
        if let shouldPopHandler = self.shouldPopHandler, !shouldPopHandler()
        {
            return false
        }
        self.popViewController(animated: true) // Needed!
        return true
    }
}

When set, your shouldPopHandler() will be called to decide whether the controller will be pop or not. When not set it will just get popped as usual.

It is a good idea to disable UINavigationControllers interactivePopGestureRecognizer as the gesture won't call your handler otherwise.


In Swift 4 or above:

override func didMove(toParent parent: UIViewController?) {
    if parent == nil {
        //"Back pressed"
    }
}

참고URL : https://stackoverflow.com/questions/18824186/trying-to-handle-back-navigation-button-action-in-ios

반응형