Подтвердить что ты не робот

Устранение отклоненияПросмотрСообщение: завершение: Push to another ViewController

Мне просто интересно, можно ли нажать на ViewController сразу после того, как я отклонил его.

Я пытался с этим:

     -(void)dismiss{
    //send information to database here

    [self dismissViewControllerAnimated:YES completion:^{
                    NSLog(@"Dismiss completed");
                    [self pushtoSingle:post_id];
                }];
}

-(void)pushtoSingle:(int)post_id{
    Single1ViewController *svc = [self.storyboard instantiateViewControllerWithIdentifier:@"SingleView"];
    svc.post_id = post_id;
    svc.page = 998;
    [self.navigationController pushViewController:svc animated:YES];
}

И это:

    -(void)dismiss{

//send information to database here

[self dismissViewControllerAnimated:YES completion:^{
                    NSLog(@"Dismiss completed");
                    Single1ViewController *svc = [self.storyboard instantiateViewControllerWithIdentifier:@"SingleView"];
                    svc.post_id = post_id;
                    svc.page = 998;
                    [self.navigationController pushViewController:svc animated:YES];
                }];
}

Но без успеха. Представление успешно отклонено, но нажатие никогда не инициализируется. Есть ли другой известный способ решения проблемы?

4b9b3361

Ответ 1

Да, я понял это. Я просто отправил уведомление после того, как я отклонил ViewController B до A, а затем получил уведомление в и нажал на C..

Отклонение в B:

[self dismissViewControllerAnimated:YES completion:^{

    [[NSNotificationCenter defaultCenter] postNotificationName:@"pushToSingle" object:nil userInfo:[NSDictionary dictionaryWithObject:[NSNumber numberWithInt:post_id1] forKey:@"post_id"]];
}];

Получение в A:

-(void)viewWillAppear:(BOOL)animated{   
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(pushToSingle:) name:@"pushToSingle" object:nil];
}

-(void)pushToSingle:(NSNotification *)notis{
    NSDictionary *dict = notis.userInfo;
    int post_id = [[dict objectForKey:@"post_id"] intValue];

    NSLog(@"pushing to single");
    Single1ViewController *svc = [self.storyboard instantiateViewControllerWithIdentifier:@"SingleView"];
    svc.post_id = post_id;
    svc.page = 998;
    [self.navigationController pushViewController:svc animated:YES];

}

Спасибо, Jacky Boy!

Ответ 2

Выньте анимацию. Вот так:

[self dismissViewControllerAnimated:NO completion:^{
                NSLog(@"Dismiss completed");
                [self pushtoSingle:post_id];
            }];

У меня были случаи, когда несколько анимаций создавали странное поведение.

Изменить 1.0:

Попробуйте следующее:

[self performSelector:@selector(pushtoSingle:) withObject:post_id afterDelay:0.3];

Изменить 2.0:

Просто заметьте сейчас... Вы отклоняете свой UIViewController, и вы пытаетесь нажать новый из вашего только что отклоненного UIViewController. Теоретически здесь:

 [self dismissViewControllerAnimated:YES completion:^{
                    NSLog(@"Dismiss completed");
                    [self pushtoSingle:post_id];
                }];

В вашем блоке завершения self будет нуль, потому что вы просто уволите его. Нажмите новый UIViewController с текущего UIViewController. Например, если ваш текущий UIViewController равен B:

A -> B

После увольнения:

A

Нажмите новый:

A -> C

Ответ 3

Это скорее добавление ответа, представленного выше, представленного robot6.

Если вы собираетесь добавлять новое представление в виде дочернего представления, вам также следует рассмотреть возможность добавления следующего к родительскому представлению.

-(void)viewDidDisappear:(BOOL)animated{
    [[NSNotificationCenter defaultCenter] removeObserver:self];

} 

В моем случае я запускал AlertView, основанный на int, переданном через уведомления NSDictionary.Тогда я снова представил одно и то же дочернее представление после принятия AlertView.

-(void)pushToSingle:(NSNotification *)notis{     
 NSDictionary *dict = notis.userInfo;
        int post_id = [[dict objectForKey:@"post_id"] intValue];
        NSLog(@"%d", post_id);


        if (post_id == 1) {
            UIAlertView *alert = [[UIAlertView alloc]

                                  initWithTitle:@"Sign Up"
                                  message:@"Are you sure you want to cancel?"
                                  delegate:self
                                  cancelButtonTitle:@"Cancel"
                                  otherButtonTitles: @"Accept", nil];
            alert.tag = 1;
            post_id = 4;
            [alert show];
        }
}

Вот что происходит.

Alert from parent view in child view

Итак, в результате вышеприведенного ответа я узнал, что в основном все, что вы делаете с точки зрения 1, снова появится в представлении вашего ребенка, как будто оно все еще находится на вашем родительском представлении, поскольку вы никогда не удаляли наблюдателя NSNotification, и наблюдатель все еще активен.

Теперь это может не вызвать проблем для всех, но он будет потреблять системные ресурсы, если вам это действительно не нужно, поскольку ARC не освободит наблюдателя до тех пор, пока родительский вид не будет активен или если вы не скажете ему сделать это в своем viewDidDisapper

Ответ 4

Категория:

class Category {
    var name: String = ""
}

FirstViewController:

class FirstViewController: UIViewController {

    func addNewCategory() {
        let category = Category()

        let secondViewController = SecondViewController(category: category)

        secondViewController.didCreateCategory = { (category: Category) in
            let thirdViewController = ThirdViewController(category: category)
            self.navigationController?.pushViewController(thirdViewController, animated: true)
        }

        let secondNavigationController = UINavigationController(rootViewController: secondViewController)
        presentViewController(secondNavigationController, animated: true, completion: nil)
    }

}

SecondViewController:

class SecondViewController: UIViewController {

    @IBOutlet weak var categoryNameTextField: UITextField!
    var didCreateCategory: ((category: Category) -> ())?
    var category: Category

    init(category: Category) {
        self.category = category
        super.init(nibName: nil, bundle: nil)
    }

    convenience required init(coder aDecoder: NSCoder) {
        self.init(coder: aDecoder)
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .Add,
            target: self, action: "createCategory")
    }

    func createCategory() {
        dismissViewControllerAnimated(true, completion: {
            self.category.name = self.categoryNameTextField.text
            self.didCreateCategory!(category: self.category)
        })
    }

}

ThirdViewController:

class ThirdViewController: UIViewController {
    var category: Category

    init(category: Category) {
        self.category = category
        super.init(nibName: nil, bundle: nil)
    }

    convenience required init(coder aDecoder: NSCoder) {
        self.init(coder: aDecoder)
    }
}