首頁 > 軟體

iOS開發實現簡單抽屜效果

2022-08-08 14:01:11

本文範例為大家分享了iOS實現簡單抽屜效果的具體程式碼,供大家參考,具體內容如下

抽屜效果的原理:其實就是把兩個子控制器新增到一個RootViewController中,將子控制器的view新增到RootViewController的view上,然後改變子控制器view的frame實現抽屜的效果。

下面直接看看我自己寫的一個小demo。

RootViewController.h

//兩個子控制器leftView和midView
@property(nonatomic,weak)UIViewController *leftView;
@property(nonatomic,weak)UIViewController *midView;

RootViewController.m

- (void)viewDidLoad {
    [super viewDidLoad];

    //將leftView和midView新增到self中作為子控制器。將他們的view新增到self.view中
    [self addChildViewController:self.leftView];
    [self.view addSubview:self.leftView.view];
    [self addChildViewController:self.midView];
    [self.view addSubview:self.midView.view];

    //設定一個按鈕點選實現抽屜效果
    UIButton *leftButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    leftButton.frame = CGRectMake(0, 50, 150, 150);
    [leftButton addTarget:self action:@selector(leftButtonPressed) forControlEvents:UIControlEventTouchUpInside];
    [leftButton setTitle:@"left" forState:UIControlStateNormal];
    [self.midView.view addSubview:leftButton];

}

-(void)leftButtonPressed
{
    //判斷抽屜是否是展開狀態
    if (self.midView.view.frame.origin.x == 0) {

        //通過動畫實現view.fram的改變
        [UIView animateWithDuration:0.3 animations:^{
            /*  W  H  螢幕實際大小宏
             * #define ScreenWidth [UIScreen mainScreen].bounds.size.width
             * #define ScreenHeight [UIScreen mainScreen].bounds.size.height
            */
            self.leftView.view.frame = CGRectMake(0, 0, W, H);
            self.midView.view.frame = CGRectMake(200, 50, W, H-50*2);

        } completion:^(BOOL finished) {
        }];

    }else{

        [UIView animateWithDuration:0.3 animations:^{

            self.midView.view.frame = CGRectMake(0, 0, W, H);

        } completion:^(BOOL finished) {
        }];
    }
}

AppDelegate.m

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

    self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    LeftViewController *leftView = [[LeftViewController alloc] init];
    MidViewController *midView = [[MidViewController alloc]init];
    RootViewController *rootView = [[RootViewController alloc]init];
    rootView.leftView = leftView;
    rootView.midView = midView;
    self.window.rootViewController = rootView;
    [self.window makeKeyAndVisible];
    return YES;
}

執行程式碼,效果圖如下:

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援it145.com。


IT145.com E-mail:sddin#qq.com