iOS Objective-c实现左右滑动切换页面
作者:zyw658000
这篇文章主要为大家详细介绍了iOS Objective-c实现左右滑动切换页面,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
本文实例为大家分享了iOS Objective-c实现左右滑动切换页面的具体代码,供大家参考,具体内容如下
ScrollView + n个view
1.storyboard布局一个ScrollView
2.拖出两个输出口,定义三个属性
@property (weak, nonatomic) IBOutlet UIScrollView *XMScrollView; @property (weak, nonatomic) IBOutlet UIView *scrollContentView; ///第一次按下 @property (nonatomic) BOOL isBeginScroll; ///开始结束滑动scroll动画 @property (nonatomic) BOOL isBeginAnimationScroll; ///开始坐标 @property (nonatomic) NSInteger beginX;
3.在viewDidAppear中重新设置scrollContentView的布局宽和tableVIew大小和位置
///遍历布局 for (NSLayoutConstraint *constraint in self.scrollContentView.constraints) { ///判断布局是不是自己想要的 NSLayoutAttribute类型 if (constraint.firstAttribute == NSLayoutAttributeWidth) { [constraint setConstant:self.view.frame.size.width*3]; } } [self.tableView1 setFrame:CGRectMake(0, 0, self.view.frame.size.width, scrollViewContentViewFrame.size.height)]; [self.tableView2 setFrame:CGRectMake(self.view.frame.size.width, 0, self.view.frame.size.width, scrollViewContentViewFrame.size.height)]; [self.tableView3 setFrame:CGRectMake(self.view.frame.size.width*2, 0, self.view.frame.size.width, scrollViewContentViewFrame.size.height)];
4.添加scrollView的代理方法
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{ ///开始滑动scrollView self.isBeginScroll = YES; ///开始滑动scrollView的位置 self.beginX = scrollView.contentOffset.x;; } - (void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset{ ///停下自动滑动scrollView [self.XMScrollView setContentOffset:CGPointZero animated:YES]; ///结束滑动scrollView self.isBeginScroll = NO; ///开始滑动动画 self.isBeginAnimationScroll = YES; } ///结束滑动动画 - (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView{ if (self.isBeginAnimationScroll) { CGFloat currentX = scrollView.contentOffset.x; NSInteger page = currentX/self.view.frame.size.width; ///判断到哪一页了,加载数据 switch (page) { case 0: break; case 1: break; case 2: break; default: break; } } self.isBeginAnimationScroll = NO; }
5.在viewDidLoad中添加监听
///页面切换ScrollView self.XMScrollView.delegate = self; [self addObserver:self forKeyPath:@"isBeginScroll" options:NSKeyValueObservingOptionNew context:nil];
6.通过监听实现滑动结束后自动滑动
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context{ if (!self.isBeginScroll) { CGFloat offSetX = self.XMScrollView.contentOffset.x; NSInteger scale = (int)(offSetX/self.view.frame.size.width); if (offSetX >= self.beginX) { [self.XMScrollView setContentOffset:CGPointMake((scale+1)*self.view.frame.size.width, 0) animated:YES]; } if (offSetX < self.beginX) { if (self.beginX >= self.view.frame.size.width){ [self.XMScrollView setContentOffset:CGPointMake((scale)*self.view.frame.size.width, 0) animated:YES]; } } } }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。