59 - Swift 之图片浏览器

一 、 前言

图像浏览器功能是提供给用户查看应有的信息图像,不重复的循环查看。像这种功能常见于 App 的首页轮播图 、商品图片的查看等。

二 、图片浏览器包含的知识点

  • 轻扫手势(UISwipeGestureRecognizer)的创建、添加,使用。

  • 闭包作为参数回调的实现。

  • 动画的添加 (CATransition)

  • (UIAlertController) 如何在一个 View 类中显示。

  • 数组的循环遍历

  • 数的取绝对值和余数

三 、图片浏览器的关键代码分析

1> 重写图片浏览器的(init(frame: CGRect))方法

// 重写对象的方法

override init(frame: CGRect) {
    super.init(frame: frame)
    // 打开图像的交互
    self.isUserInteractionEnabled = true
    // 添加图像滑动手势
    let leftSwipeGestureRecognizer = UISwipeGestureRecognizer.init(target: self, action: #selector(swipeMethod(_ :)))
    leftSwipeGestureRecognizer.direction = .left
    self.addGestureRecognizer(leftSwipeGestureRecognizer)
    
    let rightSwipeGestureRecognizer = UISwipeGestureRecognizer.init(target: self, action: #selector(swipeMethod(_ :)))
    rightSwipeGestureRecognizer.direction = .right
    self.addGestureRecognizer(rightSwipeGestureRecognizer)
    
    // 添加点击手势
    let tapGestureRecognizer = UITapGestureRecognizer.init(target: self, action: #selector(tapGestureMethod(_ :)))
    self.addGestureRecognizer(tapGestureRecognizer)
    
    // 初始化对象
    self.image = UIImage.init(named: "0.jpg")
}

required init?(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
}

2> 图片浏览器对象上轻扫手势的实现

// TODO : 向左或向右轻扫手势事件
func swipeMethod(_ swipeGestureRecognizer:UISwipeGestureRecognizer) -> Void {
    var isdirection =  true
    // 判断手势的方向
    if swipeGestureRecognizer.direction == .left {
        selecdIndex += 1
        isdirection = true
    }else if swipeGestureRecognizer.direction == .right {
        selecdIndex -= 1
        isdirection = false
    }
    self.transitionsAnimation(layer: self.layer, isDirection: isdirection)
}

3> 图片浏览器的对象转场动画

// MARK : 图像滑动的转场
func transitionsAnimation(layer:CALayer , isDirection: Bool) -> Void {
    let transition = CATransition.init()
    // 设置动画开始的进度
    transition.startProgress = 0.0
    // 设置动画结束的进度
    transition.endProgress = 1.0
    // 设置动画进行的时间
    transition.duration = 0.25
    // 动画的类型
    transition.type = "push"
    // 动画的方向
    transition.subtype = isDirection == true ? kCATransitionFromRight:kCATransitionFromLeft
    // 添加图像
    self.image = (self.imgaeArray[abs(selecdIndex)%self.imgaeArray.count] as! UIImage)
    indexCBFun(abs(selecdIndex)%self.imgaeArray.count)
    // 添加动画
    layer.add(transition, forKey: "NetWork小贱")
}

4> 图像的点击事件的实现方法

// TODO : 图像点击的事件
func tapGestureMethod(_ tapGestureRecognizer:UITapGestureRecognizer) -> Void {
    let AlertView = UIAlertController.init(title: "温馨提示", message: String.init(format: "您选择第%d个美女", (abs(selecdIndex)%self.imgaeArray.count)+1), preferredStyle: .alert)
    let AlertAction = UIAlertAction.init(title: "确定", style: .cancel, handler: nil)
    AlertView.addAction(AlertAction)
    UIApplication.shared.keyWindow?.rootViewController?.present(AlertView, animated: true, completion: nil)
    
}

5> 对象的使用方法

// 创建数据
let imgaeArrays = NSMutableArray.init(capacity: 0)
for i in 0..<6 {
    let image = UIImage.init(named: String.init(format: "%d.jpg", i))
    imgaeArrays.add(image!)
}
let sf = ShufflingFigure.init(frame: self.view.frame)
sf.imgaeArray = imgaeArrays as Array
sf.indexCBFun = { (index) in
    if self.numberLable != nil {
        self.numberLable.text = String.init(format: "%d/6", index+1)
    }
}
self.view.addSubview(sf)

四 、图片浏览器的效果

Untitled.gif

五、完整代码

1> 轮播图对象的实现

//
//  ShufflingFigure.swift
//  轮播图
//
//  Created by MAC on 2017/8/7.
//  Copyright © 2017年 NetworkCode小贱. All rights reserved.
//

import UIKit

// block 回调


class ShufflingFigure: UIImageView {
    // 存储图像的数组
    var imgaeArray = Array<Any>.init()
    var selecdIndex = 0
    typealias callBackFunc = (_ indexV:Int)->()
    var indexCBFun : callBackFunc!
    
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        // 打开图像的交互
        self.isUserInteractionEnabled = true
        // 添加图像滑动手势
        let leftSwipeGestureRecognizer = UISwipeGestureRecognizer.init(target: self, action: #selector(swipeMethod(_ :)))
        leftSwipeGestureRecognizer.direction = .left
        self.addGestureRecognizer(leftSwipeGestureRecognizer)
        
        let rightSwipeGestureRecognizer = UISwipeGestureRecognizer.init(target: self, action: #selector(swipeMethod(_ :)))
        rightSwipeGestureRecognizer.direction = .right
        self.addGestureRecognizer(rightSwipeGestureRecognizer)
        
        // 添加点击手势
        let tapGestureRecognizer = UITapGestureRecognizer.init(target: self, action: #selector(tapGestureMethod(_ :)))
        self.addGestureRecognizer(tapGestureRecognizer)
        
        // 初始化对象
        self.image = UIImage.init(named: "0.jpg")
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    
    // TODO : 向左或向右轻扫手势事件
    func swipeMethod(_ swipeGestureRecognizer:UISwipeGestureRecognizer) -> Void {
        var isdirection =  true
        // 判断手势的方向
        if swipeGestureRecognizer.direction == .left {
            selecdIndex += 1
            isdirection = true
        }else if swipeGestureRecognizer.direction == .right {
            selecdIndex -= 1
            isdirection = false
        }
        self.transitionsAnimation(layer: self.layer, isDirection: isdirection)
    }
    
    
    // TODO : 图像点击的事件
    func tapGestureMethod(_ tapGestureRecognizer:UITapGestureRecognizer) -> Void {
        let AlertView = UIAlertController.init(title: "温馨提示", message: String.init(format: "您选择第%d个美女", (abs(selecdIndex)%self.imgaeArray.count)+1), preferredStyle: .alert)
        let AlertAction = UIAlertAction.init(title: "确定", style: .cancel, handler: nil)
        AlertView.addAction(AlertAction)
        UIApplication.shared.keyWindow?.rootViewController?.present(AlertView, animated: true, completion: nil)
        
    }
    
    // MARK : 图像滑动的转场
    func transitionsAnimation(layer:CALayer , isDirection: Bool) -> Void {
        let transition = CATransition.init()
        // 设置动画开始的进度
        transition.startProgress = 0.0
        // 设置动画结束的进度
        transition.endProgress = 1.0
        // 设置动画进行的时间
        transition.duration = 0.25
        // 动画的类型
        transition.type = "push"
        // 动画的方向
        transition.subtype = isDirection == true ? kCATransitionFromRight:kCATransitionFromLeft
        // 添加图像
        self.image = (self.imgaeArray[abs(selecdIndex)%self.imgaeArray.count] as! UIImage)
        indexCBFun(abs(selecdIndex)%self.imgaeArray.count)
        // 添加动画
        layer.add(transition, forKey: "NetWork小贱")
    }
    
    /*
    // Only override draw() if you perform custom drawing.
    // An empty implementation adversely affects performance during animation.
    override func draw(_ rect: CGRect) {
        // Drawing code
    }
    */

}

2> 调用完整代码

//
//  ViewController.swift
//  轮播图
//
//  Created by MAC on 2017/8/7.
//  Copyright © 2017年 NetworkCode小贱. All rights reserved.
//

import UIKit

class ViewController: UIViewController {

    var numberLable :UILabel!
    override func viewDidLoad() {
        super.viewDidLoad()
        // 创建数据
        let imgaeArrays = NSMutableArray.init(capacity: 0)
        for i in 0..<6 {
            let image = UIImage.init(named: String.init(format: "%d.jpg", i))
            imgaeArrays.add(image!)
        }
        let sf = ShufflingFigure.init(frame: self.view.frame)
        sf.imgaeArray = imgaeArrays as Array
        sf.indexCBFun = { (index) in
            if self.numberLable != nil {
                self.numberLable.text = String.init(format: "%d/6", index+1)
            }
        }
        self.view.addSubview(sf)
        self.createLable()
        
    }
    
    func createLable() -> Void {
        if self.numberLable == nil {
            self.numberLable = UILabel.init(frame: CGRect.init(x: self.view.frame.width - 80, y: 30, width: 60, height: 30))
            self.numberLable.textAlignment = .center
            self.numberLable.font = UIFont.systemFont(ofSize: 20)
            self.numberLable.text = String.init(format: "%d/%d", 0+1,6)
            self.numberLable.textColor = UIColor.white
            self.numberLable.backgroundColor = UIColor.magenta
            self.numberLable.layer.masksToBounds = true
            self.numberLable.layer.cornerRadius = 6
            self.view.addSubview(self.numberLable)
        }
    }
    

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 221,198评论 6 514
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 94,334评论 3 398
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 167,643评论 0 360
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 59,495评论 1 296
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 68,502评论 6 397
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 52,156评论 1 308
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,743评论 3 421
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,659评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 46,200评论 1 319
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 38,282评论 3 340
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 40,424评论 1 352
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 36,107评论 5 349
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,789评论 3 333
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 32,264评论 0 23
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,390评论 1 271
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,798评论 3 376
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 45,435评论 2 359

推荐阅读更多精彩内容