iOS中分段控制器與UIScrollView結合使用 – iPhone手機開發 iPhone軟體開發教學課程

指定根視圖:

 

    // 設置window的根視圖控制器
    self.window.rootViewController = [[UINavigationController alloc] initWithRootViewController:[RootViewController new]];

定義屬性

 

 

#import RootViewController.h
#import FirstViewController.h
#import SecondTableViewController.h
@interface RootViewController ()
@property (nonatomic, strong) UISegmentedControl *segmentedControl;
@property (nonatomic, strong) UIScrollView *scrollView;
@property (nonatomic, strong) FirstViewController *firstVC;
@property (nonatomic, strong) SecondTableViewController *secondTVC;
@end

@implementation RootViewController

創建實現:

 

 

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    // 適應scrollView
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    self.segmentedControl = [[UISegmentedControl alloc] initWithItems:@[@first, @second]];
    self.navigationItem.titleView = self.segmentedControl;
    [self.segmentedControl addTarget:self action:@selector(segmentedControlAction:) forControlEvents:UIControlEventValueChanged];
    self.segmentedControl.selectedSegmentIndex = 0;
    
    // 創建scrollView
    self.scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 64, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height - 64)];
    [self.view addSubview:self.scrollView];
    // 設置scrollView的內容
    self.scrollView.contentSize = CGSizeMake([UIScreen mainScreen].bounds.size.width * 2, [UIScreen mainScreen].bounds.size.height - 64);
    self.scrollView.pagingEnabled = YES;
    self.scrollView.bounces = NO;
    
    // 創建控制器
    self.firstVC = [FirstViewController new];
    self.secondTVC = [[SecondTableViewController alloc] initWithStyle:UITableViewStylePlain];
    // 添加為self的子控制器
    [self addChildViewController:self.firstVC];
    [self addChildViewController:self.secondTVC];
    self.firstVC.view.frame = CGRectMake(0, 0, self.scrollView.frame.size.width, CGRectGetHeight(self.scrollView.frame));
    self.secondTVC.view.frame = CGRectMake([UIScreen mainScreen].bounds.size.width, 0, self.scrollView.frame.size.width, CGRectGetHeight(self.scrollView.frame));
    [self.scrollView addSubview:self.firstVC.view];
    [self.scrollView addSubview:self.secondTVC.view];
    
    // 設置scrollView的代理
    self.scrollView.delegate = self;
}

 

分段控制器點擊方法

 

- (void)segmentedControlAction:(UISegmentedControl *)sender
{
    [self.scrollView setContentOffset:CGPointMake(sender.selectedSegmentIndex * self.scrollView.frame.size.width, 0) animated:NO];
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    NSInteger n = scrollView.contentOffset.x / scrollView.frame.size.width;
    self.segmentedControl.selectedSegmentIndex = n;
}

first/和second分別為UIViewController和UITableViewController隻設顏色即可看效果(這裡不做創建)

 

最終效果:

 

 

 

發佈留言