iPhone щелкает правой кнопкой (как iTunes) - PullRequest
5 голосов
/ 17 июля 2009

Я пытаюсь переключаться между двумя представлениями. Это просто, код приведен ниже, но я также хочу одновременно перевернуть кнопку, используемую для переворота.

Вы можете увидеть это поведение в приложении iPod при воспроизведении дорожки; нажатие на кнопку переворачивания переключает обложку и список дорожек, но одновременно переворачивает кнопку.

Это страница на контроллере навигации, и кнопка, которую я хочу щелкнуть, - rightBarButtonItem.

Вот код, который у меня есть. Это переворачивает представление, но не вправо BarButton.

[UIView setAnimationBeginsFromCurrentState: YES];
[UIView setAnimationDuration: 0.5f];
[UIView setAnimationCurve: UIViewAnimationCurveEaseInOut];
showingBackside = !showingBackside;
if (showingBackside) {
    [UIView setAnimationTransition: UIViewAnimationTransitionFlipFromLeft
                           forView: self.view
                             cache: YES];
    [self.view addSubview: backside.view];
    [frontside.view removeFromSuperview];
} else {
    [UIView setAnimationTransition: UIViewAnimationTransitionFlipFromRight
                           forView: self.view
                             cache: YES];
    [self.view addSubview: frontside.view];
    [backside.view removeFromSuperview];
}
// flip image, too
NSString *newImage = showingBackside ? @"backside.png" : @"frontside.png";
[(self.navigationItem.rightBarButtonItem) setImage: [UIImage imageNamed: newImage]];
[UIView commitAnimations];

(Код переворачивания изображения здесь может не скомпилироваться; я добавил его после, чтобы попытаться объяснить, что я пытался сделать.)

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

Как мне это сделать? Какое представление я анимирую, и я делаю это как часть того же блока анимации или как отдельный? Буду признателен за любые советы, я определенно пока не разбираюсь в анимации.

Ответы [ 3 ]

5 голосов
/ 17 июля 2009

Здесь обсуждается , но решение не такое элегантное.

Прежде всего, поскольку UIBarButtonItem не является потомком UIView, вы, вероятно, не можете использовать анимации UIKit непосредственно на UIBarButtonItem. Однако вы можете попробовать установить customView и анимировать его. Вы можете использовать один и тот же блок анимации.

2 голосов
/ 29 апреля 2012

Просто используйте пользовательский UIView для правой кнопки навигации, которая содержит две кнопки для переключения между ними.

Вы можете использовать прямой подход к созданию пользовательского UIView, который отображается как элемент правой кнопки навигации. Этот UIView должен содержать две кнопки UIB, между которыми вы хотите переключиться. Помните, что кнопки UIB также являются панелями UIView, поэтому их можно переворачивать с помощью тех же переходов, с которыми можно перевернуть обычное представление пользовательского интерфейса, и, конечно же, их можно нажимать! Вот пример кода, который работает:

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

// create custom category for UIViewController to allow common button creation routine, add to .m or .mm file or add to a .h file and #import that .h file
        @interface UIViewController (ButtonAndSelector)
        - (UIButton *)createUIButtonWithImage:(UIImage *)image forState:(UIControlState)state withSelector:(SEL)selector usingFrame:(CGRect)buttonImageFrame;
        @end

        @implementation UIViewController (ButtonAndSelector)
        - (UIButton *)createUIButtonWithImage:(UIImage *)buttonImage forState:(UIControlState)state withSelector:(SEL)selector usingFrame:(CGRect)buttonImageFrame
        {
            UIButton *button = [[UIButton alloc]  initWithFrame:buttonImageFrame];
            [button setBackgroundImage:buttonImage forState:state];
            [button addTarget:self action:selector forControlEvents:UIControlEventTouchUpInside];
            [button setShowsTouchWhenHighlighted:YES];
            return button;
        }
        @end

// add this to your .h file:
        @property (strong, nonatomic) UIView *coverListView;
        @property (strong, nonatomic) UIButton *listButton;
        @property (strong, nonatomic) UIButton *coverButton;

        - (void)animateCoverListButtonFlip;

// add this to your .m or .mm file to synthesize the variables:
        @synthesize coverListView;
        @synthesize listButton;
        @synthesize coverButton;

// add this to your .m or .mm file in the viewDidLoad:

        // setup right button bar (flips between list icon and coverart image)
        self.coverListView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 32, 30)];
        self.coverListView.backgroundColor = [UIColor clearColor];
        self.coverListView.opaque = NO;

        self.listButton = [self createUIButtonWithImage:[UIImage imageNamed:@"navbar_icon_tracklisting"] forState:UIControlStateNormal withSelector:@selector(showHideQueue) usingFrame:CGRectMake(0, 0, 32, 30)];
        self.listButton.backgroundColor = [UIColor clearColor];
        self.listButton.showsTouchWhenHighlighted = NO;

        self.coverButton = [self createUIButtonWithImage:[UIImage imageNamed:@"default_coverart_small"] forState:UIControlStateNormal withSelector:@selector(showHideQueue) usingFrame:CGRectMake(0, 0, 32, 30)];
        [self.coverListView addSubview:self.coverButton]; // show coverButton by default
            self.coverButton.showsTouchWhenHighlighted = NO;

        UIBarButtonItem *barButtonItem = [[UIBarButtonItem alloc] initWithCustomView:self.coverListView];
        [self.navigationItem setRightBarButtonItem:barButtonItem];


// add this to viewDidAppear if you want to flip the button when the screen appears like the build in iPod app does
        [self animateCoverListButtonFlip];

// add this routine to flip the right navigation bar custom view / buttons
        - (void)animateCoverListButtonFlip
        {
            [UIView beginAnimations:nil context:NULL];
            [UIView setAnimationDuration:0.75];    
            [UIView setAnimationTransition:([self.listButton superview] ? UIViewAnimationTransitionFlipFromLeft : UIViewAnimationTransitionFlipFromRight) forView:self.coverListView cache:YES];

            if ([self.listButton superview]) {
                [self.listButton removeFromSuperview];
                [self.coverListView addSubview:self.coverButton];
            } else {
                [self.coverButton removeFromSuperview];
                [self.coverListView addSubview:self.listButton];
            }
            [UIView commitAnimations];
        }

// when the playing album cover changes, remember to update the coverButton:
        UIImage *artworkImage; // set this to the current playing album image
        [self.coverButton setImage:artworkImage forState:UIControlStateNormal]; 

// don't forget to call the animateCoverListButtonFlip in the button click handler (shown above as showHideQueue) that shows and hides the cover/queue(list of album tracks0 - something like this:

        - (void)showHideQueue
        {    
            [self animateCoverListButtonFlip];

            /* replace the code below that is commented out here with your own code that transitions between your cover view and your list view of album tracks, this code shows my transition and references views that are not part of this example/answer, but you don't need those - you'll have your own cover view (musicPlayerView) and list view (musicQueueView) to flip between.
            [UIView beginAnimations:nil context:NULL];
            [UIView setAnimationDuration:0.75];
            [UIView setAnimationTransition:([musicQueueView superview] ? UIViewAnimationTransitionFlipFromLeft : UIViewAnimationTransitionFlipFromRight) forView:self.contentView cache:YES];

            if ([musicQueueView superview]) { // if music queue is displayed
                [musicQueueView removeFromSuperview];
                [self.contentView addSubview:musicPlayerView];
            } else {
                [musicPlayerView removeFromSuperview];
                [self.contentView addSubview:musicQueueView];
                [[musicQueueView queueTableView] reloadData];
            }
            [UIView commitAnimations];*/
        }
2 голосов
/ 17 июля 2009

Хорошо, вот что я на самом деле сделал, чтобы это исправить:

Я уже использовал пользовательский вид заголовка. Вместо использования rightBarButtonItem я расширил свой пользовательский вид.

Я создал изображение обеих сторон кнопки, в комплекте с рамкой навигации и встроил их в приложение. В моем заголовке я поставил:

  • A UIView, который будет моей заменой для правильного управления (назовите его rightControl), расположенного соответствующим образом.
  • Кнопка над UIView, которая отвечает на UIControlEventTouchUpInside и вызывает мой flipSide:.

Во время выполнения я создаю UIImageView для каждого состояния. Я добавил UIImageView s в rightControl, но скрыл тот, который не по умолчанию. Я переключаю скрытые флаги в flipSide: в выделенном анимационном блоке.

Безумно странно. Но это работает.

...