IOS / Objective-C: два изображения, показывающие одновременно в кнопке - PullRequest
0 голосов
/ 26 мая 2018

Я пытаюсь создать эффект анимации, когда кнопка UIBarButton временно меняется на другое изображение, а затем снова возвращается обратно.Я использую кнопку, созданную в раскадровке.Поскольку uibarbuttons наследуются от NSObject вместо UIView, я сначала назначаю обычную кнопку для uibarbutton.Это позволяет мне получить доступ к свойствам UIView.Все это прекрасно работает.

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

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

//I. Fade out first image
     [UIView animateWithDuration:0.2
                          delay:1.0
                        options: UIViewAnimationCurveEaseOut
                     animations:^{
                         self.hamburgerButton.customView.alpha=0;
                     }
                     completion:^(BOOL finished) {
  //II. Fade in second image.
                          [self.hamButton setBackgroundImage:nil forState:UIControlStateNormal];
                          [self.hamButton setBackgroundImage:secondImage forState:UIControlStateNormal];

                         [UIView animateWithDuration:0.6
                                               delay:0.0
                                             options: UIViewAnimationCurveEaseOut
                                          animations:^{
                                              self.hamburgerButton.customView.alpha=1;
                                          }
                                          completion:^(BOOL finished) {

    //III. Fade out second image
                               [UIView animateWithDuration:0.6
                               delay:0.0//was 2
                               options: UIViewAnimationCurveEaseOut
                               animations:^{
                               self.hamburgerButton.customView.alpha=0;
                               }
                               completion:^(BOOL finished) {

  //IV. Fade in First Image
                                [self.hamButton setBackgroundImage:firstImage forState:UIControlStateNormal];

                                [UIView animateWithDuration:0.6
                                delay:0.0//was 2
                                options: UIViewAnimationCurveEaseOut
                                animations:^{
                                self.hamburgerButton.customView.alpha=1;
                                }
                                completion:^(BOOL finished) {    
                               }];                
                               }];
                }];       
                }];

1 Ответ

0 голосов
/ 26 мая 2018

Вместо установки изображения одной и той же кнопки возьмите две отдельные кнопки.Добавьте их в UIView.Поместите ту, которая должна быть затемнена сзади, с альфа 0, а ту, которая должна быть видна спереди, с альфа 1.

При нажатии оживите альфа передней кнопки до нуля, одновременно ожививальфа второй кнопки 1. После завершения анимации переведите кнопку «назад» вперед.

Вот как это можно сделать в obj-c:

 @interface ViewController ()
@property (strong, nonatomic) IBOutlet UIBarButtonItem *barButtonItem;
@property (strong, nonatomic) UIView *customView;
@property (strong, nonatomic) UIButton *menuButton;
@property (strong, nonatomic) UIButton *closeMenuButton;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    _menuButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [_menuButton setImage:[UIImage imageNamed:@"menu"] forState:UIControlStateNormal];
    [_menuButton addTarget:self action:@selector(menuButtonTapped) forControlEvents:UIControlEventTouchUpInside];

    _closeMenuButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [_closeMenuButton setImage:[UIImage imageNamed:@"menu-back"] forState:UIControlStateNormal];
    [_closeMenuButton addTarget:self action:@selector(closeMenuButtonTapped) forControlEvents:UIControlEventTouchUpInside];
    _closeMenuButton.alpha = 0.0;

    _customView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 30, 30)];
    _closeMenuButton.frame = _customView.bounds;
    _menuButton.frame = _customView.bounds;
    [_customView addSubview:_closeMenuButton];
    [_customView addSubview:_menuButton];

    _barButtonItem.customView = _customView;
}

- (void)menuButtonTapped {
    NSLog(@"Menu button tapped");

    [UIView animateWithDuration:0.5 animations:^{
        _menuButton.alpha = 0.0;
        _closeMenuButton.alpha = 1.0;
    } completion:^(BOOL finished) {
        [_customView bringSubviewToFront:_closeMenuButton];
    }];
}

- (void)closeMenuButtonTapped {
    NSLog(@"Close menu button tapped");
    [UIView animateWithDuration:0.5 animations:^{
        _closeMenuButton.alpha = 0.0;
        _menuButton.alpha = 1.0;
    } completion:^(BOOL finished) {
        [_customView bringSubviewToFront:_menuButton];
    }];
}
@end

Вот как я добился этого в Swift:

class ViewController: UIViewController {

    @IBOutlet var barButtonItem: UIBarButtonItem!

    let menuButton = UIButton.init(type: .custom)
    let backMenuButton = UIButton(type: .custom)
    let customView = UIView(frame: CGRect(x: 0, y: 0, width: 30, height: 30))

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

        menuButton.setImage(#imageLiteral(resourceName: "menu"), for: .normal)
        menuButton.addTarget(self, action: #selector(menuButtonTapped), for: .touchUpInside)

        backMenuButton.setImage(#imageLiteral(resourceName: "menu-back"), for: .normal)
        backMenuButton.addTarget(self, action: #selector(backMenuButtonTapped), for: .touchUpInside)



        backMenuButton.frame = customView.bounds
        customView.addSubview(backMenuButton)
        backMenuButton.alpha = 0

        menuButton.frame = customView.bounds
        customView.addSubview(menuButton)

        self.barButtonItem.customView = customView
    }

    @objc func menuButtonTapped()  {
        print("Menu button tapped")
        UIView.animate(withDuration: 0.5, animations: {
            self.menuButton.alpha = 0.0
            self.backMenuButton.alpha = 1.0
        }) { (finished) in
            self.customView.bringSubview(toFront: self.backMenuButton)
        }
    }

    @objc func backMenuButtonTapped() {
        print("Back menu button tapped")
        UIView.animate(withDuration: 0.5, animations: {
            self.backMenuButton.alpha = 0.0
            self.menuButton.alpha = 1.0
        }) { (finished) in
            self.customView.bringSubview(toFront: self.menuButton)
        }
    }
}

Результат:

enter image description here

...