59 - Swift 之圖片瀏覽器

一 、 前言

圖像瀏覽器功能是提供給用戶查看應(yīng)有的信息圖像,不重復(fù)的循環(huán)查看。像這種功能常見于 App 的首頁輪播圖 、商品圖片的查看等。

二 、圖片瀏覽器包含的知識(shí)點(diǎn)

  • 輕掃手勢(shì)(UISwipeGestureRecognizer)的創(chuàng)建、添加,使用。

  • 閉包作為參數(shù)回調(diào)的實(shí)現(xiàn)。

  • 動(dòng)畫的添加 (CATransition)。

  • (UIAlertController) 如何在一個(gè) View 類中顯示。

  • 數(shù)組的循環(huán)遍歷

  • 數(shù)的取絕對(duì)值和余數(shù)

三 、圖片瀏覽器的關(guān)鍵代碼分析

1> 重寫圖片瀏覽器的(init(frame: CGRect))方法

// 重寫對(duì)象的方法

override init(frame: CGRect) {
    super.init(frame: frame)
    // 打開圖像的交互
    self.isUserInteractionEnabled = true
    // 添加圖像滑動(dòng)手勢(shì)
    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)
    
    // 添加點(diǎn)擊手勢(shì)
    let tapGestureRecognizer = UITapGestureRecognizer.init(target: self, action: #selector(tapGestureMethod(_ :)))
    self.addGestureRecognizer(tapGestureRecognizer)
    
    // 初始化對(duì)象
    self.image = UIImage.init(named: "0.jpg")
}

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

2> 圖片瀏覽器對(duì)象上輕掃手勢(shì)的實(shí)現(xiàn)

// TODO : 向左或向右輕掃手勢(shì)事件
func swipeMethod(_ swipeGestureRecognizer:UISwipeGestureRecognizer) -> Void {
    var isdirection =  true
    // 判斷手勢(shì)的方向
    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> 圖片瀏覽器的對(duì)象轉(zhuǎn)場(chǎng)動(dòng)畫

// MARK : 圖像滑動(dòng)的轉(zhuǎn)場(chǎng)
func transitionsAnimation(layer:CALayer , isDirection: Bool) -> Void {
    let transition = CATransition.init()
    // 設(shè)置動(dòng)畫開始的進(jìn)度
    transition.startProgress = 0.0
    // 設(shè)置動(dòng)畫結(jié)束的進(jìn)度
    transition.endProgress = 1.0
    // 設(shè)置動(dòng)畫進(jìn)行的時(shí)間
    transition.duration = 0.25
    // 動(dòng)畫的類型
    transition.type = "push"
    // 動(dòng)畫的方向
    transition.subtype = isDirection == true ? kCATransitionFromRight:kCATransitionFromLeft
    // 添加圖像
    self.image = (self.imgaeArray[abs(selecdIndex)%self.imgaeArray.count] as! UIImage)
    indexCBFun(abs(selecdIndex)%self.imgaeArray.count)
    // 添加動(dòng)畫
    layer.add(transition, forKey: "NetWork小賤")
}

4> 圖像的點(diǎn)擊事件的實(shí)現(xiàn)方法

// TODO : 圖像點(diǎn)擊的事件
func tapGestureMethod(_ tapGestureRecognizer:UITapGestureRecognizer) -> Void {
    let AlertView = UIAlertController.init(title: "溫馨提示", message: String.init(format: "您選擇第%d個(gè)美女", (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> 對(duì)象的使用方法

// 創(chuàng)建數(shù)據(jù)
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> 輪播圖對(duì)象的實(shí)現(xiàn)

//
//  ShufflingFigure.swift
//  輪播圖
//
//  Created by MAC on 2017/8/7.
//  Copyright ? 2017年 NetworkCode小賤. All rights reserved.
//

import UIKit

// block 回調(diào)


class ShufflingFigure: UIImageView {
    // 存儲(chǔ)圖像的數(shù)組
    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
        // 添加圖像滑動(dòng)手勢(shì)
        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)
        
        // 添加點(diǎn)擊手勢(shì)
        let tapGestureRecognizer = UITapGestureRecognizer.init(target: self, action: #selector(tapGestureMethod(_ :)))
        self.addGestureRecognizer(tapGestureRecognizer)
        
        // 初始化對(duì)象
        self.image = UIImage.init(named: "0.jpg")
    }

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

    
    // TODO : 向左或向右輕掃手勢(shì)事件
    func swipeMethod(_ swipeGestureRecognizer:UISwipeGestureRecognizer) -> Void {
        var isdirection =  true
        // 判斷手勢(shì)的方向
        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 : 圖像點(diǎn)擊的事件
    func tapGestureMethod(_ tapGestureRecognizer:UITapGestureRecognizer) -> Void {
        let AlertView = UIAlertController.init(title: "溫馨提示", message: String.init(format: "您選擇第%d個(gè)美女", (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 : 圖像滑動(dòng)的轉(zhuǎn)場(chǎng)
    func transitionsAnimation(layer:CALayer , isDirection: Bool) -> Void {
        let transition = CATransition.init()
        // 設(shè)置動(dòng)畫開始的進(jìn)度
        transition.startProgress = 0.0
        // 設(shè)置動(dòng)畫結(jié)束的進(jìn)度
        transition.endProgress = 1.0
        // 設(shè)置動(dòng)畫進(jìn)行的時(shí)間
        transition.duration = 0.25
        // 動(dòng)畫的類型
        transition.type = "push"
        // 動(dòng)畫的方向
        transition.subtype = isDirection == true ? kCATransitionFromRight:kCATransitionFromLeft
        // 添加圖像
        self.image = (self.imgaeArray[abs(selecdIndex)%self.imgaeArray.count] as! UIImage)
        indexCBFun(abs(selecdIndex)%self.imgaeArray.count)
        // 添加動(dòng)畫
        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> 調(diào)用完整代碼

//
//  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()
        // 創(chuàng)建數(shù)據(jù)
        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.
    }


}

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容