纯Swift,使用核心动画,一个ImageView就实现了轮播图,仅需四步。

先看效果:

Swift使用核心动画一个ImageView实现轮播图

纯Swift使用核心动画一个ImageView实现轮播图,仅4步 - 敏捷大拇指 - Swift使用核心动画一个ImageView实现轮播图





1、定义所需要的属性

[Swift] 纯文本查看 复制代码
@IBOutlet weak var imageV: UIImageView!//ib拖得
var array : NSArray?;
var index : NSInteger?;
var pageContoller : UIPageControl?;





2、初始化数属性和控件

[Swift] 纯文本查看 复制代码
    index = 0;
    array = ["aion01.jpg","aion02.jpg","aion03.jpg","aion04.jpg","aion05.jpg","aion06.jpg","aion07.jpg","aion08.jpg","aion09.jpg","aion10.jpg"];
    imageV.image = UIImage(named: (array?.firstObject)! as! String);
    imageV.userInteractionEnabled = true;
    addSwipGesture();
    addPageController();
    NSTimer.scheduledTimerWithTimeInterval(3, target: self, selector: "timeAction:", userInfo: nil, repeats: true);





3、添加控件和手势

[Swift] 纯文本查看 复制代码
//添加pageController
func addPageController(){
    pageContoller = UIPageControl(frame: CGRectMake(0,imageV.frame.origin.y + imageV.bounds.size.height-30,imageV.bounds.size.width,30));
    pageContoller?.numberOfPages = (array?.count)!;
    pageContoller?.currentPage = 0;
    pageContoller?.pageIndicatorTintColor = UIColor.orangeColor();
    pageContoller?.currentPageIndicatorTintColor = UIColor.whiteColor();
    self.view.addSubview(pageContoller!);
}

//添加手势
func addSwipGesture(){

    let leftSwip = UISwipeGestureRecognizer(target: self, action: "swipAction:");
    leftSwip.direction = UISwipeGestureRecognizerDirection.Left;
    imageV.addGestureRecognizer(leftSwip);

    let rightSwip = UISwipeGestureRecognizer(target: self, action: "swipAction:");
    rightSwip.direction = UISwipeGestureRecognizerDirection.Right;
    imageV.addGestureRecognizer(rightSwip);

}





4、计时器和手势及动画调用的方法

[Swift] 纯文本查看 复制代码
//计时器调用的方法
func timeAction(time:NSTimer){
    leftAnimationAction();
}
//手势调用的方法
func swipAction(swip:UISwipeGestureRecognizer){

    if swip.direction == UISwipeGestureRecognizerDirection.Left{
        leftAnimationAction();
    }else if swip.direction == UISwipeGestureRecognizerDirection.Right{
        rightAnimationAction();
    }

}
//左划方法
func leftAnimationAction(){
    index = index! + 1;
    if index! > (array?.count)! - 1{
        self.index = 0;
    }

    imageV.image = UIImage(named: (array![index!]) as! String);
    addAnimation(1);

}
//右划方法
func rightAnimationAction(){

    index = index! - 1;
    if index! < 0{
        self.index = (array?.count)! - 1;
    }
    imageV.image = UIImage(named: (array![index!]) as! String);
    addAnimation(0);

}
//添加动画
func addAnimation(isLeft : NSInteger){
    let animation = CATransition();
    animation.duration = 0.4;
    animation.type = "push";
    if isLeft == 1{
        animation.subtype = kCATransitionFromRight;
    }else{
        animation.subtype = kCATransitionFromLeft;
    }
    imageV.layer.addAnimation(animation, forKey: "transition");

    pageContoller?.currentPage = index!;

}





作者:贝尔特伦