iOS UI设计: UISegmentedControl与UIScrollView 结合使用

思路, 不同选项卡的view在storyboard里面分别创建两个viewcontroll,如图

iOS UI设计: UISegmentedControl与UIScrollView 结合使用_第1张图片


2. 注意 为每个故事版设置一个ID

iOS UI设计: UISegmentedControl与UIScrollView 结合使用_第2张图片

3. 然后在主view代码里写

//
//  ViewController.m
//  segmentview
//
//  Created by y on 15/10/25.
//  Copyright © 2015年 y. All rights reserved.
//

#import "ViewController.h"

@interface ViewController ()<UIScrollViewDelegate>
@property (weak, nonatomic) IBOutlet UIScrollView *scrollView;
@property (weak, nonatomic) IBOutlet UISegmentedControl *segmentControl;
@property (strong, nonatomic) UIView *view1;
@property (strong, nonatomic) UIView *view2;
- (IBAction)onClick:(id)sender;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // 获取主视图高度和宽度
    float height = self.view.frame.size.height;
    float width = self.view.frame.size.width;
    // scrollview
    self.scrollView.delegate = self;
    NSLog(@"width:%f,height:%f",width,height);
    self.scrollView.contentSize = CGSizeMake(width*2, height);
    self.scrollView.frame = self.view.frame;
    
    // 获取firstview和secondview
    UIStoryboard *mainStoryboard = self.storyboard;
    self.view1 = [mainStoryboard instantiateViewControllerWithIdentifier:@"view1"].view;
    self.view2 = [mainStoryboard instantiateViewControllerWithIdentifier:@"view2"].view;
    NSLog(@"view1 width:%f,height:%f",self.view1.frame.size.width,self.view1.frame.size.height);
    
    // 设置位置
    self.view1.frame = CGRectMake(0.0f, 0.0f, width, height);
    self.view2.frame = CGRectMake(width, 0.0f, width, height);
    
    [self.scrollView addSubview:self.view1];
    [self.scrollView addSubview:self.view2];

}

- (void) scrollViewDidScroll: (UIScrollView *) aScrollView
{
    CGPoint offset = aScrollView.contentOffset;
    self.segmentControl.selectedSegmentIndex = offset.x / self.view.frame.size.width;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (IBAction)onClick:(id)sender {

    self.scrollView.contentOffset = CGPointMake(self.view.frame.size.width * self.segmentControl.selectedSegmentIndex, 0.0f);
}
@end


4. 最后效果


5. 这里有个遗留问题,在ios8的 autolayout sizeclass 里面用代码设置frame 效果有问题。正在解决中

你可能感兴趣的:(ios,UI,uiscrollview)