UISegmentedControl搭配UIScrollView使用

本文介绍了一个基于iOS平台的自定义控制器实现方案,通过UISegmentedControl选择不同的视图进行展示,并支持左右滑动切换视图。文章详细展示了如何设置UIScrollView以实现平滑的页面切换效果,并通过代码片段说明了各个组件的初始化过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

实现左右滑动切换及点击切换
自用

@interface TZLSegmentController ()<UIScrollViewDelegate>
@property (nonatomic) UISegmentedControl *segmentControl;
@property (nonatomic) TZLLiveController *liveVC;
@property (nonatomic) TZLPicShowController *picShowVC;
@property (nonatomic) UIScrollView *scrollView;

@end
- (void)viewDidLoad {
    [super viewDidLoad];
    [self scrollView];
    self.segmentControl = [[UISegmentedControl alloc] initWithItems:@[@"图赏", @"直播"]];
    _segmentControl.selectedSegmentIndex = 0;
    _segmentControl.frame = CGRectMake(0, 0, 120, 28);
    _segmentControl.tintColor = [UIColor whiteColor];
    self.navigationItem.titleView = _segmentControl;

    [_segmentControl bk_addEventHandler:^(id sender) {


        self.scrollView.contentOffset = CGPointMake(self.segmentControl.selectedSegmentIndex * self.view.width, 0);

    } forControlEvents:UIControlEventValueChanged];


}

#pragma mark - UIScrollViewDelegate
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    CGFloat offset = scrollView.contentOffset.x;
    self.segmentControl.selectedSegmentIndex = offset / self.view.width;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



- (TZLLiveController *)liveVC {
    if(_liveVC == nil) {
        _liveVC = [[TZLLiveController alloc] init];
        _liveVC.view.frame = CGRectMake(self.view.width, 0, self.view.width, self.view.height);
    }
    return _liveVC;
}

- (TZLPicShowController *)picShowVC {
    if(_picShowVC == nil) {
        _picShowVC = [[TZLPicShowController alloc] init];
        _picShowVC.view.frame = CGRectMake(0, 0, self.view.width, self.view.height);
    }
    return _picShowVC;
}

- (UIScrollView *)scrollView {
    if(_scrollView == nil) {
        //注意: 千万不要用Monsery来布局,否则在scrollview中无法再刷新
        _scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, self.view.width, self.view.height)];
        [self.view addSubview:_scrollView];
        _scrollView.delegate = self;
        _scrollView.bounces = NO;
        _scrollView.pagingEnabled = YES;
        _scrollView.directionalLockEnabled = YES;

        _scrollView.contentInset = UIEdgeInsetsMake(0, 0, 0, 0);
        _scrollView.contentSize = CGSizeMake(2 * self.view.width, self.view.height);
        _scrollView.showsHorizontalScrollIndicator = NO;

        [_scrollView addSubview:self.picShowVC.view];
        [_scrollView addSubview:self.liveVC.view];   
    }
    return _scrollView;

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值