iOS图片轮播
讲解顺序:
- 效果图
- 代码
- 所用类的官方文档讲解
1、效果图
2、代码
#import "ViewController.h"
#define w self.view.frame.size.width
static BOOL order;
@interface ViewController ()<UIScrollViewDelegate>
@property (nonatomic, retain)NSTimer* myTimer;//定时器
@property (nonatomic, retain)UIPageControl *myPageControl;//页面控制
@property(nonatomic,strong)UIScrollView *scroll;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
order = YES;//正序
_scroll = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, 320, 200)];
_scroll.contentSize = CGSizeMake(w*5, 200);
_scroll.pagingEnabled = YES;
_scroll.backgroundColor = [UIColor blueColor];
_scroll.showsHorizontalScrollIndicator = NO;
_scroll.delegate = self;
[self.view addSubview:_scroll];
for(int i = 0; i<5; i++){
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(w*i, 0, w, 200)];
label.text = [NSString stringWithFormat:@"我是第%d个视图",i+1];
label.textAlignment = NSTextAlignmentCenter;
[label setBackgroundColor:[UIColor colorWithRed:arc4random()%256/255.0 green:arc4random()%256/255.0 blue:arc4random()%256/255.0 alpha:1.0]];
[_scroll addSubview:label];
}
_myPageControl = [[UIPageControl alloc] initWithFrame:CGRectMake(0, 100, w, 50)];
_myPageControl.numberOfPages = 5;//总页数
_myPageControl.currentPageIndicatorTintColor = [UIColor redColor];//选中点的颜色
_myPageControl.pageIndicatorTintColor = [UIColor whiteColor];//其它点的颜色
[self.view addSubview:_myPageControl];
//创建定时器
_myTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(changeView) userInfo:nil repeats:YES];
//添加到指定模式
[[NSRunLoop mainRunLoop] addTimer:_myTimer forMode:NSRunLoopCommonModes];
}
//滚动结束
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
float offset_X = _scroll.contentOffset.x;
_myPageControl.currentPage = offset_X / w;
}
//开始拖拽
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
[_myTimer setFireDate:[NSDate distantFuture]];
}
//结束拖拽
-(void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
[_myTimer setFireDate:[NSDate dateWithTimeInterval:1.0 sinceDate:[NSDate date]]];
}
-(void)changeView{
NSInteger page = 0;
if(order == YES){
page = _myPageControl.currentPage + 1;
if(page == _myPageControl.numberOfPages)
{
order = NO;
}
}
if(order == NO){
page = _myPageControl.currentPage - 1;
if(page == 0)
{
order = YES;
}
}
CGPoint offset = _scroll.contentOffset;
offset.x = page * _scroll.frame.size.width;
//显示指定区域
[_scroll setContentOffset:offset animated:YES];
}
-(void)viewDidDisappear:(BOOL)animated
{
[_myTimer invalidate];// 将定时器从运行循环中移除,
_myTimer = nil;// 销毁定时器
}
@end
3、官方文档讲解
NSTimer官方文档 参考作者文章
#import <Foundation/NSObject.h>
#import <Foundation/NSDate.h>
NS_ASSUME_NONNULL_BEGIN
@interface NSTimer : NSObject
//创建定时器,ti时间后启动,这种方式创建后,需要手动添加到RunLoop,参数repeats是指定是否循环执行
+ (NSTimer *)timerWithTimeInterval:(NSTimeInterval)ti invocation:(NSInvocation *)invocation repeats:(BOOL)yesOrNo;
//创建定时器,ti时间后启动,并添加到默认的RunLoop模式中
+ (NSTimer *)scheduledTimerWithTimeInterval:(NSTimeInterval)ti invocation:(NSInvocation *)invocation repeats:(BOOL)yesOrNo;
+ (NSTimer *)timerWithTimeInterval:(NSTimeInterval)ti target:(id)aTarget selector:(SEL)aSelector userInfo:(nullable id)userInfo repeats:(BOOL)yesOrNo;
+ (NSTimer *)scheduledTimerWithTimeInterval:(NSTimeInterval)ti target:(id)aTarget selector:(SEL)aSelector userInfo:(nullable id)userInfo repeats:(BOOL)yesOrNo;
+ (NSTimer *)timerWithTimeInterval:(NSTimeInterval)interval repeats:(BOOL)repeats block:(void (^)(NSTimer *timer))block API_AVAILABLE(macosx(10.12), ios(10.0), watchos(3.0), tvos(10.0));
+ (NSTimer *)scheduledTimerWithTimeInterval:(NSTimeInterval)interval repeats:(BOOL)repeats block:(void (^)(NSTimer *timer))block API_AVAILABLE(macosx(10.12), ios(10.0), watchos(3.0), tvos(10.0));
- (instancetype)initWithFireDate:(NSDate *)date interval:(NSTimeInterval)interval repeats:(BOOL)repeats block:(void (^)(NSTimer *timer))block API_AVAILABLE(macosx(10.12), ios(10.0), watchos(3.0), tvos(10.0));
- (instancetype)initWithFireDate:(NSDate *)date interval:(NSTimeInterval)ti target:(id)t selector:(SEL)s userInfo:(nullable id)ui repeats:(BOOL)rep NS_DESIGNATED_INITIALIZER;
// 启动 Timer
- (void)fire;
//设置定时器的启动时间(可以让定时器启动与停止)
@property (copy) NSDate *fireDate;
//获取定时器调用间隔时间
@property (readonly) NSTimeInterval timeInterval;
//设置误差范围
@property NSTimeInterval tolerance NS_AVAILABLE(10_9, 7_0);
// 停止 Timer ,将定时器从循环池中移除
- (void)invalidate;
// 获取定时器是否有效
@property (readonly, getter=isValid) BOOL valid;
// 获取参数信息
@property (nullable, readonly, retain) id userInfo;
@end
NS_ASSUME_NONNULL_END
UIPageControl官方文档
#import <Foundation/Foundation.h>
#import <UIKit/UIControl.h>
#import <UIKit/UIKitDefines.h>
NS_ASSUME_NONNULL_BEGIN
NS_CLASS_AVAILABLE_IOS(2_0) @interface UIPageControl : UIControl
@property(nonatomic) NSInteger numberOfPages;//指定页数,也就是显示的点数
@property(nonatomic) NSInteger currentPage; //指定当前选中的点,默认为0
@property(nonatomic) BOOL hidesForSinglePage;//当只有一页时是否显示分页控件
@property(nonatomic) BOOL defersCurrentPageDisplay; //点击控件后是否延迟更新页面
- (void)updateCurrentPageDisplay;//更新界面
- (CGSize)sizeForNumberOfPages:(NSInteger)pageCount;
@property(nullable, nonatomic,strong) UIColor *pageIndicatorTintColor ;//默认点的颜色
@property(nullable, nonatomic,strong) UIColor *currentPageIndicatorTintColor ;//当前选中的点显示的颜色
@end
NS_ASSUME_NONNULL_END
UIScrollView官方文档
#import <Foundation/Foundation.h>
#import <CoreGraphics/CoreGraphics.h>
#import <UIKit/UIView.h>
#import <UIKit/UIGeometry.h>
#import <UIKit/UIKitDefines.h>
#import <UIKit/UIRefreshControl.h>
NS_ASSUME_NONNULL_BEGIN
typedef NS_ENUM(NSInteger, UIScrollViewIndicatorStyle) {
UIScrollViewIndicatorStyleDefault,
UIScrollViewIndicatorStyleBlack,
UIScrollViewIndicatorStyleWhite
};
typedef NS_ENUM(NSInteger, UIScrollViewKeyboardDismissMode) {
UIScrollViewKeyboardDismissModeNone,
UIScrollViewKeyboardDismissModeOnDrag,
UIScrollViewKeyboardDismissModeInteractive,
} NS_ENUM_AVAILABLE_IOS(7_0);
UIKIT_EXTERN const CGFloat UIScrollViewDecelerationRateNormal NS_AVAILABLE_IOS(3_0);
UIKIT_EXTERN const CGFloat UIScrollViewDecelerationRateFast NS_AVAILABLE_IOS(3_0);
@class UIEvent, UIImageView, UIPanGestureRecognizer, UIPinchGestureRecognizer;
@protocol UIScrollViewDelegate;
NS_CLASS_AVAILABLE_IOS(2_0) @interface UIScrollView : UIView <NSCoding>
@property(nonatomic) CGPoint contentOffset;//contentView的偏移值
@property(nonatomic) CGSize contentSize; //contentView的大小
@property(nonatomic) UIEdgeInsets contentInset; //contentView四周的扩展大小
@property(nullable,nonatomic,weak) id<UIScrollViewDelegate> delegate; //代理
@property(nonatomic,getter=isDirectionalLockEnabled) BOOL directionalLockEnabled; //用来让用户每次只在一个方向上滚动,竖直或者水平
@property(nonatomic) BOOL bounces;//弹簧效果
@property(nonatomic) BOOL alwaysBounceVertical;//bounces是YES的时候才能使用,设置垂直方向的反弹是否有效
@property(nonatomic) BOOL alwaysBounceHorizontal;//bounces是YES的时候才能使用,设置水平方向的反弹是否有效
@property(nonatomic,getter=isPagingEnabled) BOOL pagingEnabled __TVOS_PROHIBITED;//contentView是否整页翻动
@property(nonatomic,getter=isScrollEnabled) BOOL scrollEnabled; //contentView是否能滚动
@property(nonatomic) BOOL showsHorizontalScrollIndicator; //是否显示水平方向的滚动条
@property(nonatomic) BOOL showsVerticalScrollIndicator;//是否显示垂直方向的滚动条
@property(nonatomic) UIEdgeInsets scrollIndicatorInsets; //滚动条在scrollerView中的位置的扩展
@property(nonatomic) UIScrollViewIndicatorStyle indicatorStyle; //滚动条样式
@property(nonatomic) CGFloat decelerationRate NS_AVAILABLE_IOS(3_0);//手指放开后的减速率
- (void)setContentOffset:(CGPoint)contentOffset animated:(BOOL)animated; //设置内容视图原点的偏移点,并设置是否有动画
- (void)scrollRectToVisible:(CGRect)rect animated:(BOOL)animated; //使rect中定义的区域可以刚好显示在滚动视图中
- (void)flashScrollIndicators; //短暂地显示滚动指示器
@property(nonatomic,readonly,getter=isTracking) BOOL tracking;//返回用户是否触摸内容并初始化滚动.(只读)
@property(nonatomic,readonly,getter=isDragging) BOOL dragging;//表明用户是否开始滚动内容。
@property(nonatomic,readonly,getter=isDecelerating) BOOL decelerating;// 返回滚动视图中的内容是否在提起手指后继续移动。(只读)
@property(nonatomic) BOOL delaysContentTouches; //布尔值,规定滚动视图是否延迟处理触摸下压手势。
@property(nonatomic) BOOL canCancelContentTouches; //布尔值,控制触摸内容视图时是否总是导致跟踪。
- (BOOL)touchesShouldBegin:(NSSet<UITouch *> *)touches withEvent:(nullable UIEvent *)event inContentView:(UIView *)view;//
- (BOOL)touchesShouldCancelInContentView:(UIView *)view;//
@property(nonatomic) CGFloat minimumZoomScale;//该值规定了内容可被缩小到多小。默认值为1.0
@property(nonatomic) CGFloat maximumZoomScale;//该值规定了内容可被放大到多大。默认值为1.0。
@property(nonatomic) CGFloat zoomScale ;//该值规定了内容当前缩放了多少。默认值是1.0。
- (void)setZoomScale:(CGFloat)scale animated:(BOOL)animated;//
- (void)zoomToRect:(CGRect)rect animated:(BOOL)animated;//
@property(nonatomic) BOOL bouncesZoom; //若该属性的值为YES,在缩放超出最大值或最小值时,滚动视图会临时播放一个稍超出限制范围的动画再返回限制大小。
@property(nonatomic,readonly,getter=isZooming) BOOL zooming; //布尔值,表明内容视图当前是否在缩。
@property(nonatomic,readonly,getter=isZoomBouncing) BOOL zoomBouncing; //布尔值,表明缩放已超过了指定接收器的缩放限制。
@property(nonatomic) BOOL scrollsToTop __TVOS_PROHIBITED; //滚动至顶部手势是触摸状态栏;当此属性为YES时,滚动视图在此手势发生时跳转至状态栏。此属性默认为YES。
@property(nonatomic, readonly) UIPanGestureRecognizer *panGestureRecognizer ;//当前用于滑动手势的手势识别器
@property(nullable, nonatomic, readonly) UIPinchGestureRecognizer *pinchGestureRecognizer ;//当前用于扩张/收缩手势的手势识别器(只读)
@property(nonatomic, readonly) UIGestureRecognizer *directionalPressGestureRecognizer ;//
@property(nonatomic) UIScrollViewKeyboardDismissMode keyboardDismissMode NS_AVAILABLE_IOS(7_0);//
@property (nonatomic, strong, nullable) UIRefreshControl *refreshControl NS_AVAILABLE_IOS(10_0) __TVOS_PROHIBITED;//
@end
@protocol UIScrollViewDelegate<NSObject>
@optional
- (void)scrollViewDidScroll:(UIScrollView *)scrollView;//已经滑动
- (void)scrollViewDidZoom:(UIScrollView *)scrollView NS_AVAILABLE_IOS(3_2);//已经缩放
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView;//开始拖动
- (void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset;//
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate;// 结束拖动
- (void)scrollViewWillBeginDecelerating:(UIScrollView *)scrollView;//开始减速
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView;//减速停止
- (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView;//滚动动画停止时执行
- (nullable UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView;//返回一个放大或者缩小的视图
- (void)scrollViewWillBeginZooming:(UIScrollView *)scrollView withView:(nullable UIView *)view;//开始放大或者缩小
- (void)scrollViewDidEndZooming:(UIScrollView *)scrollView withView:(nullable UIView *)view atScale:(CGFloat)scale;//缩放结束时
- (BOOL)scrollViewShouldScrollToTop:(UIScrollView *)scrollView; //是否支持滑动至顶部
- (void)scrollViewDidScrollToTop:(UIScrollView *)scrollView; //滑动到顶部时调用该方法
@end
NS_ASSUME_NONNULL_END
Android图片轮播
讲解顺序:
- 效果图
- 代码
1、效果图
2、代码
MainActivity文件
package com.example.work.viewpager;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import java.util.List;
import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;
public class MainActivity extends AppCompatActivity implements ViewPager.OnPageChangeListener {
private ViewPager viewPager;
private List<ImageView> images;
private List<View> points;
private int oldPosition = 0;
private int[] imageIds = new int[]{
R.drawable.f27,
R.drawable.f28,
R.drawable.f29,
R.drawable.f30
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
viewPager = (ViewPager)findViewById(R.id.viewPager);
initViews();
viewPager.setAdapter(new MyPagerAdapter());
timer.schedule(task, 1000, 1000); // 1s后执行task,经过1s再次执行
}
private void initViews(){
//显示的图片
images = new ArrayList<ImageView>();
for(int i = 0; i < imageIds.length; i++){
ImageView imageView = new ImageView(this);
imageView.setBackgroundResource(imageIds[i]);
images.add(imageView);
}
//显示的小点
points = new ArrayList<View>();
points.add(findViewById(R.id.dot_0));
points.add(findViewById(R.id.dot_1));
points.add(findViewById(R.id.dot_2));
points.add(findViewById(R.id.dot_3));
//设置默认显示的选项卡
viewPager.setCurrentItem(0);
viewPager.setOnPageChangeListener(this);
}
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
@Override
public void onPageSelected(int position) {
points.get(position).setBackgroundResource(R.drawable.p2);
points.get(oldPosition).setBackgroundResource(R.drawable.point);
oldPosition = position;
}
@Override
public void onPageScrollStateChanged(int state) {
}
//适配器
class MyPagerAdapter extends PagerAdapter{
@Override
public int getCount() {
return images.size();
}
//实例化
@Override
public Object instantiateItem(ViewGroup container, int position) {
View v = images.get(position);
container.addView(v);
return v;
}
//删除选项卡
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView(images.get(position));
}
@Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
//获取标题
public CharSequence getPageTitle(int position){
return null;
}
}
Handler handler = new Handler() {
public void handleMessage(Message msg) {
if (msg.what == 1) {
viewPager.setCurrentItem((oldPosition+1)% imageIds.length);
}
super.handleMessage(msg);
};
};
Timer timer = new Timer();
TimerTask task = new TimerTask() {
@Override
public void run() {
// 需要做的事:发送消息
Message message = new Message();
message.what = 1;
handler.sendMessage(message);
}
};
}
布局文件
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.example.work.viewpager.MainActivity">
<android.support.v4.view.ViewPager
android:id="@+id/viewPager"
android:layout_height="200dp"
android:layout_width="match_parent">
</android.support.v4.view.ViewPager>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="35dip"
android:layout_gravity="bottom"
android:background="#33000000"
android:gravity="center"
android:orientation="horizontal">
<View
android:id="@+id/dot_0"
android:layout_width="10dip"
android:layout_height="10dip"
android:layout_marginLeft="5dip"
android:layout_marginRight="5dip"
android:background="@drawable/p2"/>
<View
android:id="@+id/dot_1"
android:layout_width="10dip"
android:layout_height="10dip"
android:layout_marginLeft="5dip"
android:layout_marginRight="5dip"
android:background="@drawable/point"/>
<View
android:id="@+id/dot_2"
android:layout_width="10dip"
android:layout_height="10dip"
android:layout_marginLeft="5dip"
android:layout_marginRight="5dip"
android:background="@drawable/point"/>
<View
android:id="@+id/dot_3"
android:layout_width="10dip"
android:layout_height="10dip"
android:layout_marginLeft="5dip"
android:layout_marginRight="5dip"
android:background="@drawable/point"/>
</LinearLayout>
</LinearLayout>