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

Ios 7 просмотр с прозрачным контентом перекрывает предыдущий вид

Недавно я обновил свой проект xcode для работы с iOS 7, но я столкнулся с большой проблемой. Поскольку у всего моего приложения есть только одно фоновое изображение (добавлено UIImageView в ключевое окно), и все представления прозрачны, я сталкиваюсь с проблемой при нажатии UIViewController, потому что нажатый контроллер просмотра перекрывает предыдущий вид (вы можете увидеть его на картинке здесь: http://grab.by/qp0k). Я могу предсказать, что это связано с тем, что в iOS 7 был изменен push-переход, поскольку теперь он скользит на половину экрана. Может быть, кто-нибудь знает, как решить эту проблему?

Вот как я устанавливаю свои ключевые окна

  self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]]; 
 UIImageView *background = [[UIImageView alloc]initWithFrame:[[UIScreen mainScreen] bounds]];
 background.image = [UIImage imageNamed:@"background.png"]; 
UINavigationController *navi = [[UINavigationController alloc]initWithRootViewController:self.viewController];
self.window.rootViewContro‌​ller = navi;
 [self.window makeKeyAndVisible];

Впоследствии, когда пользователь нажимает кнопку "начать тренировку", я всегда нажимаю свой следующий вид:

workoutView *w = [[workoutView alloc]initWithNibName:@"workoutView" bundle:nil];
        [self.navigationController pushViewController:w animated:YES];
4b9b3361

Ответ 1

Я решил проблему, выполнив новый UINavigationControllerDelegate Method animationControllerForOperation.

Например:

- (id<UIViewControllerAnimatedTransitioning>)navigationController:(UINavigationController     *)navigationController
                              animationControllerForOperation:(UINavigationControllerOperation)operation
                                           fromViewController:(UIViewController *)fromVC
                                             toViewController:(UIViewController *)toVC
{

PushTransition* transition = [PushTransition new];
[transition setNavigationControllerOperation: operation];

return transition;
}

PushTransition - это класс, который реализует протокол UIViewControllerAnimatedTransitioning и два метода transitionDuration и animateTransition из этого протокола. Кроме того, я добавил свойство для передачи операции (говорит мне, является ли это push или pop-переход).

Просто поместите код анимации для перемещения представлений в animateTransition следующим образом:

// the containerView is the superview during the animation process.
UIView *container = transitionContext.containerView;

UIViewController *fromVC = [transitionContext viewControllerForKey:UITransitionContextFromViewControllerKey];
UIViewController *toVC = [transitionContext viewControllerForKey:UITransitionContextToViewControllerKey];

UIView *fromView = fromVC.view;
UIView *toView = toVC.view;
CGFloat containerWidth = container.frame.size.width;

// Set the needed frames to animate.

CGRect toInitialFrame = [container frame];
CGRect fromDestinationFrame = fromView.frame;

if ([self navigationControllerOperation] == UINavigationControllerOperationPush)
{
    toInitialFrame.origin.x = containerWidth;
    toView.frame = toInitialFrame;
    fromDestinationFrame.origin.x = -containerWidth;
}
else if ([self navigationControllerOperation] == UINavigationControllerOperationPop)
{
    toInitialFrame.origin.x = -containerWidth;
    toView.frame = toInitialFrame;
    fromDestinationFrame.origin.x = containerWidth;
}

// Create a screenshot of the toView.
UIView *move = [toView snapshotViewAfterScreenUpdates:YES];
move.frame = toView.frame;
[container addSubview:move];

[UIView animateWithDuration:TRANSITION_DURATION delay:0
     usingSpringWithDamping:1000 initialSpringVelocity:1
                    options:0 animations:^{
                        move.frame = container.frame;
                        fromView.frame = fromDestinationFrame;
                    }
                 completion:^(BOOL finished) {
                     if (![[container subviews] containsObject:toView])
                     {
                         [container addSubview:toView];
                     }

                     toView.frame = container.frame;
                     [fromView removeFromSuperview];
                     [move removeFromSuperview];
                     [transitionContext completeTransition: YES];
                 }];

описал это, и вы можете это сделать. Кроме того, вы можете сделать любую push или поп-анимацию, которая вам нравится.

Ответ 2

Я сделал это.

-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [self.view setAlpha:0];
}

Не забудьте повторно установить альфу, когда вернетесь.

- (void) viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.view setAlpha:1];
}

Ответ 3

Я исправил это, выполнив это при инициализации представления:

self.view.clipsToBounds = YES;

Ответ 4

Возможно, вам захочется заглянуть в новую функцию iOS7, которая позволит вам определить собственные пользовательские переходы UIViewController. Посмотрите в документах для UIViewControllerTransitioningDelegate. Кроме того, здесь ссылка на статью об этом: http://www.doubleencore.com/2013/09/ios-7-custom-transitions/

Ответ 5

А, теперь я понимаю эту проблему. Вы были правы, похоже, что предыдущий UIViewController не скрывается после перехода (из-за нового эффекта перехода).

Кажется, что нет никакого SDK-метода для управления этим поведением. Не доработав приложение до того, что фон не будет неподвижным, вам, вероятно, придется перевернуть свою собственную навигацию. OSNavigationController - это полная повторная реализация UINavigationController, которая может помочь вам. Если они не обновлены до перехода на iOS 7, вам, вероятно, будет хорошо идти. Если они есть, вы всегда можете использовать более старую версию.

Ответ 6

У меня была та же проблема. Попробуйте загрузить фоновое изображение в методе init. Для меня это работало (иногда): Например:

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        self.view.backgroundColor = [UIColor whiteColor];
        [self.imageBack setImage:[UIImage imageNamed:@"mayBack.png"]];
    }
    return self;
}

Однако вы могли видеть проблески.. Лучшее решение, которое я нашел, помимо внедрения нового протокола перехода iOS7, заключается в реализации категории и использовании этой категории всякий раз, когда вам это нужно. Вы можете найти ответ здесь

Ответ 7

Настройка изображения на цвет фона решила проблему:

self.view.backgroundColor = 
            [UIColor colorWithPatternImage:[UIImage imageNamed:@"mainback.png"]];

Ответ 8

Взгляните на категорию UINavigationController в этом сообщении (это решило мою проблему):

fooobar.com/questions/140165/...

Ответ 9

Реквизит для @snoersnoer.


Вот код в Swift 3.

func navigationController(_ navigationController: UINavigationController, animationControllerFor operation: UINavigationControllerOperation, from fromVC: UIViewController, to toVC: UIViewController) -> UIViewControllerAnimatedTransitioning? {

    let pushTransition = SUPushTransition()
    pushTransition.navigationControllerOperation = operation
    return pushTransition
}

func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {

    // the containerView is the superview during the animation process.
    let container = transitionContext.containerView

    let fromVC = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.from)
    let toVC = transitionContext.viewController(forKey:UITransitionContextViewControllerKey.to);

    if let from = fromVC,
        let fromView = from.view,
        let to = toVC,
        let toView = to.view {

        let containerWidth = container.frame.size.width

        // Set the needed frames to animate.

        var toInitialFrame = container.frame
        var fromDestinationFrame = fromView.frame

        if self.navigationControllerOperation == .push {
            toInitialFrame.origin.x = containerWidth;
            toView.frame = toInitialFrame;
            fromDestinationFrame.origin.x = -containerWidth;
        }
        else if self.navigationControllerOperation == .pop {
            toInitialFrame.origin.x = -containerWidth;
            toView.frame = toInitialFrame;
            fromDestinationFrame.origin.x = containerWidth;
        }

        // Create a screenshot of the toView.
        if let move = toView.snapshotView(afterScreenUpdates: true) {

            move.frame = toView.frame
            container.addSubview(move)

            UIView.animate(withDuration: Constants.MainPage.navControllerDuration, delay: 0.0, usingSpringWithDamping: 1000, initialSpringVelocity: 1, options: .curveEaseInOut, animations: {
                move.frame = container.frame;
                fromView.frame = fromDestinationFrame;
            }, completion: { (finished) in

                if finished {

                    if !container.subviews.contains(toView) {
                        container.addSubview(toView)
                    }

                    toView.frame = container.frame

                    fromView.removeFromSuperview()
                    move.removeFromSuperview()

                    transitionContext.completeTransition(true)
                }

            })

        }

    }

}

Приветствия.