UISegmentedControl分段控制 跳轉各介面
阿新 • • 發佈:2018-12-31
一、對於分段控制元件的三方外掛有很多,個人在閒著的時候也就寫了一個,適合初級的人員上手。 二、先談一下思路: 整體的效果是 UISegmentedControl + UIView 做介面切換 建立好一個分段控制元件 ----> 建立分段控制元件的點選響應事件 ----> 建立需要UIview的數量 ----> 在載入UIView的時候進行判斷 ----> 點選分段控制元件跳轉各個UIView跳轉 ----> 完成 三、廢話不多說,直接上程式碼: 1、在.h 檔案裡面建立分段控制器的屬性,以及將要載入UIView數量的屬性 #import <UIKit/UIKit.h> #import "oneUIView.h" #import "twoUIView.h" #import "threeUIView.h" @interface ViewController : UIViewController @property (nonatomic,strong)UISegmentedControl *itemControl;//分段控制器 @property (nonatomic,strong) oneUIView *one; @property (nonatomic,strong) twoUIView *two; @property (nonatomic,strong) threeUIView *three; @end 2、在.m檔案裡面實現 // // ViewController.m // test // // Created by on 16/3/10. // Copyright © 2016年 liu. All rights reserved. // #import "ViewController.h" #define SCREEN_W [[UIScreen mainScreen]bounds].size.width // 獲取螢幕的寬 #define SCREEN_H [[UIScreen mainScreen]bounds].size.height //獲取螢幕的高 // // ViewController.m // test // // Created by on 16/3/10. // Copyright © 2016年 liu. All rights reserved. // #import "ViewController.h" #define SCREEN_W [[UIScreen mainScreen]bounds].size.width // 獲取螢幕的寬 #define SCREEN_H [[UIScreen mainScreen]bounds].size.height //獲取螢幕的高 @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; self.view.backgroundColor = [UIColor whiteColor];//設定背景顏色 [self.view addSubview:self.itemControl];//新增分段控制器 [self.view addSubview:self.one];//在頁面載入時,新增首頁UIView } #pragma mark -- 分段控制器點選事件 - (void)respondsToSegemnt:(UISegmentedControl*)sender { switch (sender.selectedSegmentIndex) { case 0: { [self.two removeFromSuperview]; //分段控制器設定預設選中第一段時,應該顯示的是首頁的UIview, 所以後面的UIview應該被移除掉。如果不移除掉,那麼首頁的UIView將會被後面的UIView覆蓋 [self.three removeFromSuperview]; NSLog(@"1111111111"); } break; case 1: { [self.view addSubview:self.two]; //在首頁做了移除操作,當選中第二段時,就應該做UIView的新增操作。直接把首頁覆蓋,達到介面跳轉的效果 NSLog(@"2222222222"); } break; case 2: { [self.view addSubview:self.three]; NSLog(@"33333333"); } break; default: break; } } #pragma mark -- 懶載入初始化分段控制器、UIView - (UISegmentedControl *)itemControl { if (!_itemControl) { NSArray *arrary = @[@"one",@"two",@"three"]; _itemControl = [[UISegmentedControl alloc]initWithItems:arrary]; _itemControl.frame = CGRectMake(0, 50, SCREEN_W, 40); _itemControl.selectedSegmentIndex = 0; [_itemControl addTarget:self action:@selector(respondsToSegemnt:) forControlEvents:UIControlEventValueChanged]; } return _itemControl; } - (oneUIView *)one { if (!_one) { _one = [[oneUIView alloc]initWithFrame:CGRectMake(0, 100, self.view.bounds.size.width, self.view.bounds.size.height)]; } return _one; } - (twoUIView *)two { if (!_two) { _two = [[twoUIView alloc]initWithFrame:CGRectMake(0, 100, self.view.bounds.size.width, self.view.bounds.size.height)]; } return _two; } - (threeUIView *)three { if (!_three) { _three = [[threeUIView alloc]initWithFrame:CGRectMake(0, 100, self.view.bounds.size.width, self.view.bounds.size.height)]; } return _three; } @end