Swift-14.Swift UI(二)

本章包含内容:

  • 表格视图
  • 媒体与动画

五、表格视图

表格视图小节包含以下内容:

  • UITableView的简单使用
  • UITableView滑动到指定单元格
  • 自定义UITableView单元格Accessory样式
  • 删除UITableView单元格
  • 插入UITableView单元格
  • 调整UITableView单元格的顺序

1. UITableView的简单使用

import UIKit

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
    //创建一个数组作为表格的数据来源
    var weeks = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.createTableView()
    }
    
    func createTableView() {
        
        let rect = CGRect(x: 0, y: 40, width: 375, height: 627)
        let tableView = UITableView(frame: rect)
        
        tableView.delegate = self
        tableView.dataSource = self
        
        self.view.addSubview(tableView)
    }
    
    //MARK: UITableViewDataSource, UITableViewDelegate
    //行数
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return weeks.count
    }
    
    //行高
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 80
    }
    
    //返回cell
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let identifier = "reusedCell"
        var cell = tableView.dequeueReusableCell(withIdentifier: identifier)
        if (cell == nil) {
            cell = UITableViewCell(style: .default, reuseIdentifier: identifier)
        }
        cell?.textLabel?.text = weeks[indexPath.row]
        cell?.detailTextLabel?.text = "Detail Information here."
        
        //读取图片素材
        let star = UIImage(named: "zan_h")
        let starGray = UIImage(named: "zan_n")
        //将灰色图片作为单元格的默认图标
        cell?.imageView?.image = starGray
        //将红色图片作为单元格的高亮图标
        cell?.imageView?.highlightedImage = star
        
        
        #if true
            //间隔背景颜色
            if indexPath.row % 2 == 0 {
                cell?.backgroundColor = UIColor.purple
            }else{
                cell?.backgroundColor = UIColor.red
            }
            
        #else
            //如果处于第二行,则设置单元格的背景颜色为黄色
            if indexPath.row == 1 {
                cell?.backgroundColor = UIColor.yellow
            }
        #endif
        
        return cell!
    }
    

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}
Swift-14.Swift UI(二)_第1张图片
UITableView的简单使用

2. UITableView滑动到指定单元格

import UIKit

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {

    let months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        let rect = CGRect(x: 0, y: 40, width: 375, height: 627)
        let tableView = UITableView(frame: rect)
        
        tableView.delegate = self
        tableView.dataSource = self
        
        //初始化一个索引路径对象,用来表示表格中的第一个段落和第十二行的位置
        let indexPath = IndexPath(row: 11, section: 0)
        //调用表格对象的滚动到指定位置方法,表格将以动画的方法,滑动到指定的索引位置
        tableView.scrollToRow(at: indexPath, at: UITableViewScrollPosition.top, animated: true)
        
        self.view.addSubview(tableView)
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return months.count
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 80
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let identifier = "reusedCell"
        var cell = tableView.dequeueReusableCell(withIdentifier: identifier)
        
        if cell == nil {
            cell = UITableViewCell(style: .default, reuseIdentifier: identifier)
        }
        
        cell?.textLabel?.text = months[indexPath.row]
        
        return cell!
    }
    

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


}

3. 自定义UITableView单元格Accessory样式

import UIKit

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {

    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        let rect = CGRect(x: 0, y: 40, width: 375, height: 627)
        let tableView = UITableView(frame: rect)
        
        tableView.delegate = self
        tableView.dataSource = self

        self.view.addSubview(tableView)
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 7
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let identifier = "reusedCell"
        var cell = tableView.dequeueReusableCell(withIdentifier: identifier)
        
        if cell == nil {
            cell = UITableViewCell(style: .default, reuseIdentifier: identifier)
        }
        
        cell?.textLabel?.text = "Cell item \(indexPath.row)"
        
        return cell!
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 80
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        //获取表格中被点击的单元格
        let cell = tableView.cellForRow(at: indexPath)
        //如果被点击的单元格,没有显示附加图标,则显示复选标记图标,表示当前单元格处于选中状态
        if cell?.accessoryType == UITableViewCellAccessoryType.none {
            cell?.accessoryType = UITableViewCellAccessoryType.checkmark
        }else{
            //如果被点击的单元格,已经存在附加图标,则隐藏附加图标,表示当前党元格处于非选中状态。
            cell?.accessoryType = UITableViewCellAccessoryType.none
        }
    }
    

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


}
Swift-14.Swift UI(二)_第2张图片
自定义UITableView单元格Accessory样式

4. 删除UITableView单元格

import UIKit

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {

    var months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]

    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        let rect = CGRect(x: 0, y: 40, width: 375, height: 627)
        let tableView = UITableView(frame: rect)
        
        tableView.delegate = self
        tableView.dataSource = self
        
        self.view.addSubview(tableView)
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return months.count
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 80
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let identifier = "reusedCell"
        var cell = tableView.dequeueReusableCell(withIdentifier: identifier)
        
        if cell == nil {
            cell = UITableViewCell(style: .default, reuseIdentifier: identifier)
        }
        
        cell?.textLabel?.text = months[indexPath.row]
        
        return cell!
    }

    
    func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCellEditingStyle {
        //设置单元格的编辑模式为删除模式
        return UITableViewCellEditingStyle.delete
    }
    
    //添加一个代理方法,用来响应单元格的删除事件
    func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
        //如果编辑模式为删除,执行
        if editingStyle == UITableViewCellEditingStyle.delete {
            //获取待删除的单元格在段落中的行数
            let rowNum = indexPath.row
            //从数组中删除单元格的内容,以保证数据的一致性
            months.remove(at: rowNum)
            //创建一个包含待删除单元格位置信息的数组
            let indexPaths = [indexPath]
            //再从表格视图中,清除该单元格
            tableView.deleteRows(at: indexPaths, with: UITableViewRowAnimation.automatic)
        }
    }
    

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

5.插入UITableView单元格

import UIKit

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {

    var months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]

    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        let rect = CGRect(x: 0, y: 40, width: 375, height: 627)
        let tableView = UITableView(frame: rect)
        
        tableView.delegate = self
        tableView.dataSource = self
        tableView.setEditing(true, animated: false)
        
        self.view.addSubview(tableView)
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return months.count
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 80
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let identifier = "reusedCell"
        var cell = tableView.dequeueReusableCell(withIdentifier: identifier)
        
        if cell == nil {
            cell = UITableViewCell(style: .default, reuseIdentifier: identifier)
        }
        
        cell?.textLabel?.text = months[indexPath.row]
        
        return cell!
    }

    
    func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCellEditingStyle {
        //设置单元格的编辑模式为删除模式/插入模式
//        return UITableViewCellEditingStyle.delete
        return UITableViewCellEditingStyle.insert
    }
    
    //添加一个代理方法,用来响应单元格的删除事件
    func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
        //如果编辑模式为删除,执行
        if editingStyle == UITableViewCellEditingStyle.delete {
            //获取待删除的单元格在段落中的行数
            let rowNum = indexPath.row
            //从数组中删除单元格的内容,以保证数据的一致性
            months.remove(at: rowNum)
            //创建一个包含待删除单元格位置信息的数组
            let indexPaths = [indexPath]
            //再从表格视图中,清除该单元格
            tableView.deleteRows(at: indexPaths, with: UITableViewRowAnimation.automatic)
        }
        
        //如果编辑模式为插入,执行
        if editingStyle == UITableViewCellEditingStyle.insert {
            let rowNum = indexPath.row
            months.insert("Honey Moon", at: rowNum)
            //创建一个包含待插入单元格位置信息的数组
            let indexPaths = [indexPath]
            //再从表格视图中,插入该单元格
            tableView.insertRows(at: indexPaths, with: UITableViewRowAnimation.automatic)

        }
    }
    

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

6.调整UITableView单元格的顺序

import UIKit

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {

    var months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]

    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        let rect = CGRect(x: 0, y: 40, width: 375, height: 627)
        let tableView = UITableView(frame: rect)
        
        tableView.delegate = self
        tableView.dataSource = self
        tableView.setEditing(true, animated: false)
        
        self.view.addSubview(tableView)
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return months.count
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 80
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let identifier = "reusedCell"
        var cell = tableView.dequeueReusableCell(withIdentifier: identifier)
        
        if cell == nil {
            cell = UITableViewCell(style: .default, reuseIdentifier: identifier)
        }
        
        cell?.textLabel?.text = months[indexPath.row]
        
        return cell!
    }

    
    func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCellEditingStyle {
        //设置单元格的编辑模式为删除模式/插入模式/拖动换行
//        return UITableViewCellEditingStyle.delete
//        return UITableViewCellEditingStyle.insert
        return UITableViewCellEditingStyle.none
    }
    
    //添加一个代理方法,用来设置单元格是否允许拖动换行
    func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
        return true
    }
    
    //添加一个代理方法,用来响应单元格的移动时间
    func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) {
        //获取单元格移动前的位置
        let fromRow = sourceIndexPath.row
        //获取单元格移动后的位置
        let toRow = destinationIndexPath.row
        //获取数组在单元格移动前的对象
        let obj = months[fromRow]
        //删除数组中单元格移动前的位置的对象
        months.remove(at: fromRow)
        //然后在数组的目标位置插入一份删除的对象,以同步数据源
        months.insert(obj, at: toRow)
    }
    
    //添加一个代理方法,用来响应单元格的删除事件
    func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
        //如果编辑模式为删除,执行
        if editingStyle == UITableViewCellEditingStyle.delete {
            //获取待删除的单元格在段落中的行数
            let rowNum = indexPath.row
            //从数组中删除单元格的内容,以保证数据的一致性
            months.remove(at: rowNum)
            //创建一个包含待删除单元格位置信息的数组
            let indexPaths = [indexPath]
            //再从表格视图中,清除该单元格
            tableView.deleteRows(at: indexPaths, with: UITableViewRowAnimation.automatic)
        }
        
        //如果编辑模式为插入,执行
        if editingStyle == UITableViewCellEditingStyle.insert {
            let rowNum = indexPath.row
            months.insert("Honey Moon", at: rowNum)
            //创建一个包含待插入单元格位置信息的数组
            let indexPaths = [indexPath]
            //再从表格视图中,插入该单元格
            tableView.insertRows(at: indexPaths, with: UITableViewRowAnimation.automatic)
        }
        
    }
    

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


}

六、媒体与动画

媒体与动画小节包含以下内容:

  • 使用图形上下文按一定比例缩放图片
  • 使用图形上下文转换图片为灰度图
  • 使用CoreImage框架设置图片的单色效果、更改图片的色相、添加马赛克
  • 使用UIBlurEffect给图片添加模糊效果
  • 使用CATransaction Reveal制作动画
  • 使用CATransaction Push制作动画
  • UIView视图的动画
  • 使用SystemSoundld播放简短声音和使用AudioPlayer播放音乐(含背景音乐)
  • 使用MediaPlayer框架播放影片

1. 使用图形上下文按一定比例缩放图片

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        
        let image = UIImage(named: "b_icon")
        let scaledImage = scaleImage(image: image!, newSize: CGSize(width: 180, height: 180))
        
        let imageView = UIImageView(image: scaledImage)
        imageView.center = CGPoint(x: 160, y: 160)
        
        self.view.addSubview(imageView)
        
    }
    
    //首先创建一个方法,传递一个图像参数,和一个缩放比例参数,实现将图像缩放至指定比例的功能
    func scaleImage(image:UIImage, newSize:CGSize) -> UIImage {
        //获得源图像的尺寸属性
        let imageSize = image.size
        //获得源图像的宽度数值
        let width = imageSize.width
        //获得源图像的高度数值
        let height = imageSize.height
        
        //计算图像新尺寸与旧尺寸的宽高比例
        let widthFactor = newSize.width/width
        let heightFactor = newSize.height/height
        //获取最小的那个比例
        let scaleFactor = (widthFactor

2.使用图形上下文转换图片为灰度图

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        
        //1.使用图形上下文按一定比例缩放图片
        /*
        let image = UIImage(named: "b_icon")
        let scaledImage = scaleImage(image: image!, newSize: CGSize(width: 180, height: 180))
        
        let imageView = UIImageView(image: scaledImage)
        imageView.center = CGPoint(x: 160, y: 160)
        
        self.view.addSubview(imageView)
         */
        
        //2.使用图形上下文按一定比例缩放图片
        let image = UIImage(named: "b_icon")
        let grayedImage = self.grayImage(image: image!)
        
        let imageView = UIImageView(image: grayedImage)
        imageView.center = CGPoint(x: 160, y: 160)
        self.view.addSubview(imageView)

        
    }
    
    //MARK:1. 使用图形上下文按一定比例缩放图片
    //首先创建一个方法,传递一个图像参数,和一个缩放比例参数,实现将图像缩放至指定比例的功能
    func scaleImage(image:UIImage, newSize:CGSize) -> UIImage {
        //获得源图像的尺寸属性
        let imageSize = image.size
        //获得源图像的宽度数值
        let width = imageSize.width
        //获得源图像的高度数值
        let height = imageSize.height
        
        //计算图像新尺寸与旧尺寸的宽高比例
        let widthFactor = newSize.width/width
        let heightFactor = newSize.height/height
        //获取最小的那个比例
        let scaleFactor = (widthFactor UIImage {
        //获得源图像的尺寸属性
        let imageSize = image.size
        //获得源图像的宽度数值
        let width = imageSize.width
        //获得源图像的高度数值
        let height = imageSize.height
        
        //创建灰度色彩空间对象。各种设备对待颜色的方式都不同,颜色必须有一个相关的色彩空间。否则,图形上下文将不知道如何解释相关的颜色值
        let spaceRef = CGColorSpaceCreateDeviceGray()
        /*
         参数1:指向要渲染的绘制内存的地址
         参数2、3:分别表示宽度和高度
         参数4:表示内存中像素的每个组件的位数
         参数5:表示每一行,在内存所占的比特数
         参数6:表示上下文使用的颜色空间
         参数7:表示是否包含alpha通道
         */
        let context = CGContext(data: nil, width: Int(width), height: Int(height), bitsPerComponent: 8, bytesPerRow: 0, space: spaceRef, bitmapInfo: CGBitmapInfo().rawValue)!
        
        let rect = CGRect(x: 0, y: 0, width: imageSize.width, height: imageSize.height)
        //在灰度上下文中画入图片
        context.draw(image.cgImage!, in: rect)
        //从上下文中,获取并声称转为灰度的图片
        let grayImage = UIImage(cgImage: context.makeImage()!)
        
        return grayImage
    }

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

3.使用CoreImage框架设置图片的单色效果、更改图片的色相、添加马赛克、遍历所有滤镜

import UIKit
import CoreImage//该框架提供了强大和高效的图像处理功能,用来对基于像素的图像进行分析、操作和特效处理

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        
//        self.singleColor()
//        self.changeColor()
//        self.mosaic()
        self.all()
    }
    
    //单色滤镜效果
    func singleColor() {
        let image = UIImage(named: "b_icon")
        let imageView = UIImageView(image: image)
        self.view.addSubview(imageView)
        
        //初始化一个CoreImage图像对象
        let ciImage = CIImage(image: image!)
        //初始化一个颜色对象,并设置其颜色值为棕色
        let color = UIColor(red: 0.8, green: 0.6, blue: 0.4, alpha: 1)
        //初始化一个滤镜对象,并设置滤镜类型为单色调滤镜
        let filter = CIFilter(name: "CIColorMonochrome")
        //设置单色调滤镜的输入颜色值
        filter?.setValue(color, forKey: kCIInputColorKey)
        //设置单色调滤镜的颜色浓度值
        filter?.setValue(1.0, forKey: kCIInputIntensityKey)
        //设置需要应用单色调滤镜的图像
        filter?.setValue(ciImage, forKey: kCIInputImageKey)
        //获得应用单色调滤镜后的图像
        let outImage = filter?.outputImage
        
        //更改图像视图的内容,为应用滤镜后的图像
        if let outImg = outImage {
            imageView.image = UIImage(ciImage: outImg)
        }
    }
    
    //更改图片的色相
    func changeColor() {
        let image = UIImage(named: "b_icon")
        let imageView = UIImageView(image: image)
        self.view.addSubview(imageView)

        //初始化一个CoreImage图像对象
        let ciImage = CIImage(image:image!)
        //初始化一个滤镜对象,并设置滤镜类型为色相调整滤镜
        let filter = CIFilter(name: "CIHueAdjust")
        //设置色相调整滤镜的输入角度值为30度
        filter?.setValue(3.14/6, forKey: kCIInputAngleKey)
        //设置需要应用色相调整滤镜的图像
        filter?.setValue(ciImage, forKey: kCIInputImageKey)
        //获得应用色相调整后的图像
        let outImage = filter?.outputImage
        
        //更改图像视图的内容
        imageView.image = UIImage(ciImage: outImage!)
        
    }

    //添加马赛克
    func mosaic() {
        let image = UIImage(named: "b_icon")
        let imageView = UIImageView(image: image)
        self.view.addSubview(imageView)
        
        //初始化一个CoreImage图像对象
        let ciImage = CIImage(image:image!)
        //初始化一个滤镜对象,并设置滤镜类型为像素化滤镜
        let filter = CIFilter(name: "CIPixellate")
        //设置像素话滤镜,采用默认的配置选项
        filter?.setDefaults()
        //设置需要应用像素话滤镜的图像
        filter?.setValue(ciImage, forKey: kCIInputImageKey)
        //获得应用像素话滤镜后的图像
        let outImage = filter?.outputImage
        
        imageView.image = UIImage(ciImage: outImage!)
    }
    
    //遍历系统提供的所有滤镜
    func all() {
        //获取系统内置滤镜,并将其放到数组里
        let builtInFilters = CIFilter.filterNames(inCategory: kCICategoryBuiltIn)
        for filter in builtInFilters {
            //根据滤镜名称,获取对应的滤镜
            let filter = CIFilter(name: filter as String)
            //获得滤镜所有的属性
            let attributes = filter!.attributes
            print("[\(filter)]\n")
            print(attributes)
            print("\n --------------------- \n")
        }
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


}
Swift-14.Swift UI(二)_第3张图片
CoreImage框架设置图片

4.使用UIBlurEffect给图片添加模糊效果

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        let image = UIImage(named: "b_icon")
        let imageView = UIImageView(image: image)
        self.view.addSubview(imageView)

        //从8.0版本开始,系统提供了模糊效果的功能,这里判断如果系统版本大于或者等于8.0,则使用模糊效果
        if #available(iOS 8.0, *) {
            //初始化一个模糊效果对象。模糊效果对象可以帮助你快速制作类似于导航栏,通知中心或者控制中心的毛玻璃效果
            let blur = UIBlurEffect(style: .light)
            //初始化一个基于模糊效果的视觉效果视图
            let blurView = UIVisualEffectView(effect: blur)
            blurView.frame = CGRect(x: 40, y: 40, width: 200, height: 200)
            blurView.layer.cornerRadius = 30
            blurView.layer.masksToBounds = true
            imageView.addSubview(blurView)
        }else{
            print("UIBlurEffect is only available on iOS8.0 or newer.")
        }
        
    }

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


}
Swift-14.Swift UI(二)_第4张图片
使用UIBlurEffect给图片添加模糊效果

5.使用CATransaction Reveal制作动画

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        
        let imageView = UIImageView(frame: CGRect(x: 0, y: 100, width: 375, height: 567))
        imageView.image = UIImage(named: "b_icon")
        self.view.addSubview(imageView)
        
        /*
         你可以使用两种方法,来实现动画效果,一种是视图层面的,另一种是使用过滤动画,它实现了层的过滤动画,因此可以进行更低层次的控制
         */
        let animation = CATransition()
        //动画时长
        animation.duration = 2
        //动画的播放速度为由慢至快
        animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseOut)
        //动画的类型为渐显动画
        animation.type = kCATransitionReveal
        
        //将动画指定给图像视图的图层
        imageView.layer.add(animation, forKey: "Reveal")
    }

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

6.使用CATransaction Push制作动画

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        
        let imageView = UIImageView(frame: CGRect(x: 0, y: 100, width: 375, height: 567))
        imageView.image = UIImage(named: "b_icon")
        self.view.addSubview(imageView)
        
        //初始化一个过渡动画实例
        let animation = CATransition()
        //时长
        animation.duration = 2
        //动画播放速度为由慢至快
        animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseOut)
        //设置动画的类型为入场动画
        animation.type = kCATransitionPush
        
        imageView.layer.add(animation, forKey: "Push")
    }

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

7.UIView视图的动画

import UIKit

enum AnimatonType:Int {
    case 块动画
    case 卷曲动画
    case 检测动画的结束事件
}

class ViewController: UIViewController {

    var animtaonType:Int?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
//        self.viewBlockAnimation(animatonType: AnimatonType.块动画.rawValue)
//        self.viewBlockAnimation(animatonType: AnimatonType.卷曲动画.rawValue)
//        self.viewBlockAnimation(animatonType: AnimatonType.检测动画的结束事件.rawValue)
        self.frameAnimation()
        
    }
    
    
    func viewBlockAnimation(animatonType:Int) {
        let imageView = UIImageView(frame: CGRect(x: 50, y: 50, width: 220, height: 320))
        imageView.image = UIImage(named: "b_icon")
        imageView.tag = 1
        
        self.view.addSubview(imageView)
        
        let button = UIButton(type: .system)
        button.frame = CGRect(x: 50, y: 400, width: 220, height: 44)
        button.backgroundColor = UIColor.lightGray
        button.setTitle("Tap", for: UIControlState())
        button.addTarget(self, action: #selector(ViewController.playAnimation), for: .touchUpInside)
        self.view.addSubview(button)
        
        self.animtaonType = animatonType
    }
    
    func playAnimation() {
        //发出开始视图动画的请求,标志着视图动画块的开始。在它和提交动画请求之间,可以定义动画的各种展现方式
        UIView.beginAnimations(nil, context: nil)
        //设置动画的播放速度为淡入淡出
        UIView.setAnimationCurve(.easeOut)
        //设置动画的时长
        UIView.setAnimationDuration(5)
        //设置动画从视图当前状态开始播放
        UIView.setAnimationBeginsFromCurrentState(true)
        
        
        //1.UIView视图的动画块
        if self.animtaonType == AnimatonType.块动画.rawValue {
            
            let view = self.view.viewWithTag(1)
            //设置动画类型为翻转动画
            UIView.setAnimationTransition(.flipFromRight, for: view!, cache: true)
            //调用提交动画方法
            UIView.commitAnimations()

        }else if self.animtaonType == AnimatonType.卷曲动画.rawValue//2.UIView视图卷曲动画的制作
        {
            
            let view = self.view.viewWithTag(1)
            //设置动画类型为卷曲动画
            UIView.setAnimationTransition(.curlUp, for: view!, cache: true)
            //调用提交动画方法
            UIView.commitAnimations()

        }else if self.animtaonType == AnimatonType.检测动画的结束事件.rawValue//3.检测UIView视图动画的结束事件
        {
            let view = self.view.viewWithTag(1)
            //设置动画类型为翻转动画
            UIView.setAnimationTransition(.flipFromRight, for: view!, cache: true)
            //设置视图的目标位置为50,50.目标尺寸为0,0
            view?.frame = CGRect(x: 50, y: 50, width: 0, height: 0)
            //同时设置动画的代理对象为当前视图控制器类
            UIView.setAnimationDelegate(self)
            //设置动画结束时执行的方法
            UIView.setAnimationDidStop("animationStop")
            //调用提交动画方法
            UIView.commitAnimations()
        }
    }
    
    //响应动画结束事件
    func animationStop() {
        print("Animation stop")
        self.view.viewWithTag(1)?.removeFromSuperview()
    }
    
    //4.使用UIImageView制作帧动画
    func frameAnimation() {
        //初始化一个数组,用来存放图片素材
        var images = [UIImage]()
        for i in 1...60 {

            let name = String(format: "dropdown_anim000\(i)")
            images.append(UIImage(named: name)!)
        }
        
        let imageView = UIImageView(frame: CGRect(x: 0, y: 60, width: 40, height: 40))
        //设置图像视图的动画图片属性
        imageView.animationImages = images
        //设置帧动画的时长为5
        imageView.animationDuration = 5
        //设置动画循环次数,0为无限循环播放
        imageView.animationRepeatCount = 0
        //开始帧动画的播放
        imageView.startAnimating()
    
        self.view.addSubview(imageView)
    }
    
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}

8.使用SystemSoundld播放简短声音和使用AudioPlayer播放音乐(含背景音乐)

import UIKit
import AudioToolbox//导入音频工具箱框架
import AVFoundation//导入需要使用的流媒体基础框架,它能收集各种多媒体数据,这些数据可以来自不同的输入设备,比如摄像机、录音等

class ViewController: UIViewController {

    //初始化音频播放对象,并将音频播放对象作为视图控制器类的属性
    var audioPlayer:AVAudioPlayer!
    
    override func viewDidLoad() {
        super.viewDidLoad()
//        self.audioFunc1()
        self.audioPlayer1()
    }

    //1.使用SystemSoundld播放简短声音
    func audioFunc1() {
        //声明一个系统声音标识类型的声音变量
        var soundId:SystemSoundID = 0
        //获取沙箱目录中,声音文件的所在路径
        let path = Bundle.main.path(forResource: "dingdong", ofType: "wav")
        //将字符串路径转换为网址路径
        let soundUrl = URL(fileURLWithPath: path!)
        //对于按钮音,下来菜单音等较短的声音,以及震动效果,可以使用系统音频服务来播放。
        AudioServicesCreateSystemSoundID(soundUrl as CFURL, &soundId)
        //播放声音
        AudioServicesPlaySystemSound(soundId)
    }
    
    //2.使用AVAudioPlayer播放音乐
    func audioPlayer1() {
        //获取沙箱目录中音频文件所在的路径
        let path = Bundle.main.path(forResource: "test", ofType: "mp3")
        //将字符串路径转换为网址路径
        let soundUrl = URL(fileURLWithPath: path!)
        
        //在音频播放前,首先创建一个异常捕捉语句
        do {
            //对音频播放对象进行初始化,并加载指定的音频文件
            try self.audioPlayer = AVAudioPlayer(contentsOf: soundUrl)
            //设置音频播放对象的音量大小
            self.audioPlayer.volume = 1.0
            //设置音频播放的次数,-1为无限循环播放
            self.audioPlayer.numberOfLoops = -1
            //背景音乐
            self.audioPlayer.prepareToPlay()
            //开始播放
            self.audioPlayer.play()
        } catch {
            print(error)
        }
    }
    
    
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}

9.使用MediaPlayer框架播放影片

import UIKit
import MediaPlayer //导入媒体播放器框架,该框架允许您访问音频和视频资源。它是音频和视频文件的播放器,无需你控制其如何工作,但是让您很容易处理音频或视频文件

class ViewController: UIViewController {

    //新建一个视频播放器播放属性,用于播放视频
    var mediaPlayer:MPMoviePlayerController = MPMoviePlayerController()
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        //在视频文件播放前,首先创建一个异常捕捉语句
        do {
            //获取沙箱目录中,视频文件的所在路径
            let path = Bundle.main.path(forResource: "cocosvideo", ofType: "mp4")
            //将字符串路径转换为url
            let movieUrl = URL(fileURLWithPath: path!)
            //对视频播放对象,进行初始化,并加载指定的视频文件
            mediaPlayer = MPMoviePlayerController(contentURL: movieUrl)
            //设置视频播放模式为全屏播放
            mediaPlayer.controlStyle = MPMovieControlStyle.fullscreen
            //设置视频播放的窗口大小,匹配视图控制器的根视图
            mediaPlayer.view.frame = self.view.bounds
            //设置视频播放的开始时间
            mediaPlayer.initialPlaybackTime = -1
            //开始播放
            mediaPlayer.play()
            self.view.addSubview(mediaPlayer.view)
            //添加一个通知,监听视频播放是否结束
            NotificationCenter.default.addObserver(self, selector: #selector(movieFinished(notify:)), name: .MPMoviePlayerPlaybackDidFinish, object: mediaPlayer)
        } catch  {
            print(error)
        }
    }
    
    //创建一个方法,响应视频播放的结束事件
    func movieFinished(notify:NSNotification) {
        print("Movie ends.")
        //获得视频播放控制器
        let player = notify.object
        //取消通知的监听,释放资源
        NotificationCenter.default.removeObserver(self, name: NSNotification.Name.MPMoviePlayerPlaybackDidFinish, object: player)
    }

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

你可能感兴趣的:(Swift-14.Swift UI(二))