English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Как реализовать простой эффект ящика с помощью 100 строк кода в iOS

Введение

Простое внедрение эффекта «дверцы» в iOS используется многими приложениями, и в Интернете много примеров. В этой статье мы реализуем это с помощью простого кода, и те, кто этого хочет, могут вместе учиться.

Ниже приведен пример

Пример кода таков

#import <UIKit/UIKit.h>
@interface MainViewController : UIViewController
+ (instancetype)mainViewControllerWithLeftViewController:(UIViewController *)leftViewController withMainPageViewController:(UIViewController *)mainPageViewController;
@end
#import "MainViewController.h"
#define KWidth self.view.frame.size.width
#define KHeight self.view.frame.size.height
@interface MainViewController ()
@property (nonatomic,strong)UIViewController *leftVC;
@property (nonatomic,strong)UIViewController *centerVC;
@property (nonatomic,assign)BOOL isSlider;
@property (nonatomic,strong)UIView *corverView;
@end
@implementation MainViewController
+ (instancetype)mainViewControllerWithLeftViewController:(UIViewController *)leftViewController withMainPageViewController:(UIViewController *)mainPageViewController{
  MainViewController *mainVC = [[MainViewController alloc] init];
  mainVC.leftVC = leftViewController;
  mainVC.centerVC = mainPageViewController;
  return mainVC;
}
- (void)viewDidLoad{
  [super viewDidLoad];
  self.isSlider = NO;
  self.view.backgroundColor = [UIColor whiteColor];
  [self addChildViewController:self.leftVC];
  [self.view addSubview:self.leftVC.view];
  [self addChildViewController:self.centerVC];
  [self.view addSubview:self.centerVC.view];
  // Дать жесты для левого и основного видов
  [self addGestureForView];
}
// Добавить покрытие для основного вида
- (void)addCorverView{
  if (self.corverView) {
    [self.corverView removeFromSuperview];
    self.corverView = nil;
  }
  self.corverView = [[UIView alloc] initWithFrame:self.centerVC.view.bounds];
  _corverView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.0];
  [self.centerVC.view addSubview:self.corverView];
}
// Удалить покрытие основного вида
- (void)removeCoverView{
  if (self.corverView) {
    [self.corverView removeFromSuperview];
    self.corverView = nil;
  }
}
// Дать жесты для левого и основного видов
- (void)addGestureForView{
  UISwipeGestureRecognizer *rightGesture = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(swipeRightAction:)];
  rightGesture.direction = UISwipeGestureRecognizerDirectionRight;
  [self.centerVC.view addGestureRecognizer:rightGesture];
  UISwipeGestureRecognizer *leftGesture = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(swipeLeftAction:)];
  leftGesture.direction = UISwipeGestureRecognizerDirectionLeft;
  [self.centerVC.view addGestureRecognizer:leftGesture];
  UISwipeGestureRecognizer *leftVCLeftSwipeGesture = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(leftVCLeftSwipeAction:)];
  leftVCLeftSwipeGesture.direction = UISwipeGestureRecognizerDirectionLeft;
  [self.leftVC.view addGestureRecognizer:leftVCLeftSwipeGesture];
}
- (void)swipeRightAction:(id)sender{
  [self moveView:self.centerVC.view scale:0.8 panValue:KWidth];
  self.isSlider = YES;
  [self addCorverView];
}
- (void)swipeLeftAction:(id)sender{
  [self moveView:self.centerVC.view scale:1 panValue:KWidth / 2];
  self.isSlider = NO;
  [self removeCoverView];
}
- (void)leftVCLeftSwipeAction:(id)sender{
  [self moveView:self.centerVC.view scale:1 panValue:KWidth / 2];
  self.isSlider = NO;
  [self removeCoverView];
}
// Перемещение и масштабирование视图
- (void)moveView:(UIView *)view scale:(CGFloat)scale panValue:(CGFloat)value{
  [UIView beginAnimations:nil context:nil];
  view.transform = CGAffineTransformScale(CGAffineTransformIdentity,scale,scale);
  view.center = CGPointMake(value, view.center.y);
  [UIView commitAnimations];
}
@end

Резюме

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

Заявление: содержимое этой статьи взято из Интернета, авторские права принадлежат соответствующему автору, контент был предоставлен пользователями Интернета в добровольном порядке, сайт не обладает правами собственности, не был отредактирован вручную и не несет ответственности за соответствующие юридические последствия. Если вы обнаружите контент,涉嫌侵犯版权, пожалуйста, отправьте письмо по адресу: notice#oldtoolbag.com (во время отправки письма замените # на @) для сообщения о нарушении,并提供 соответствующие доказательства. При подтверждении факта нарушения сайт незамедлительно удалят涉嫌侵权的内容.

Основной учебник
Рекомендуется для просмотра