分类 触摸事件 下的文章

swift简易画板

控制器类
//
//  ViewController.swift
//  简易画板
//
//  Created by admin on 16/1/25.
//  Copyright © 2016年 jin. All rights reserved.
//

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var drawingBoard: DrawingBoard!
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }
    @IBAction func back(sender: AnyObject) {
        self.drawingBoard.back()
    }
    @IBAction func clear(sender: AnyObject) {
        self.drawingBoard.clear()
    }
    @IBAction func save(sender: AnyObject) {
        self.drawingBoard.save()
    }
    @IBAction func selectColor(sender: UIButton) {
        self.drawingBoard.selectColor(sender.backgroundColor!)
    }
}
画板类
//
//  DrawingBoard.swift
//  简易画板
//
//  Created by admin on 16/1/25.
//  Copyright © 2016年 jin. All rights reserved.
//

import UIKit
// 线结构体
struct Line {
    let color:UIColor
    var points:[CGPoint] = []
}
// 画板类,使用上下文方式画
class DrawingBoard: UIView {
    // 线的集合
    var lines:[Line] = []
    // 当前选择的颜色
    var lineColor:UIColor = UIColor.blackColor()
    // 开始触摸方法,在开始触摸的时候新初始化一个线结构体
    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
        let tempLine = Line(color: self.lineColor, points: [])
        lines.append(tempLine)
    }
    // 移动的时候给当前的线结构体添加点
    override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) {
        let touch = (touches as NSSet).anyObject()
        // 添加当前线的结构体到线集合数组
        lines[self.lines.count - 1].points.append((touch?.locationInView(touch?.view))!)
        self.setNeedsDisplay()
    }
    // 画
    override func drawRect(rect: CGRect) {
        // 先获取上下文,在添加点
        let context = UIGraphicsGetCurrentContext()
        // 设置线的样式
        CGContextSetLineCap(context, CGLineCap.Round)
        CGContextSetLineJoin(context, CGLineJoin.Round)
        CGContextSetLineWidth(context, 10)
        for var j = 0;j < self.lines.count;j++
        {
            self.lines[j].color.set()
            for var i = 0;i < self.lines[j].points.count;i++
            {
                let point:CGPoint = (self.lines[j].points[i])
                if i == 0
                {
                    CGContextMoveToPoint(context, point.x, point.y)
                }
                else
                {
                    CGContextAddLineToPoint(context, point.x, point.y)
                }
            }
            CGContextStrokePath(context)
        }
    }
    // 回退
    func back()
    {
        if self.lines.count > 0
        {
            self.lines.removeLast()
            self.setNeedsDisplay()
        }
    }
    // 清屏
    func clear()
    {
        self.lines = []
        self.setNeedsDisplay()
    }
    // 保存颜色
    func save()
    {
        // 开始位图上下文
        UIGraphicsBeginImageContextWithOptions(self.bounds.size, false, 0)
        // 画图
        self.setNeedsDisplay()
        // 获取当前图片
        let context = UIGraphicsGetCurrentContext()
        self.layer.renderInContext(context!)
        let image = UIGraphicsGetImageFromCurrentImageContext()
        // 转换成 NSData 数据
        let resImage = UIImagePNGRepresentation(image)
        // 保存
        resImage?.writeToFile("/Users/admin/Desktop/DrawingBoard.png", atomically: true)
    }
    // 
    func selectColor(color:UIColor)
    {
        self.lineColor = color
    }
}
画板类,UIBezierPath方式画
//
//  DrawBoardBezierPath.swift
//  简易画板
//
//  Created by admin on 16/1/25.
//  Copyright © 2016年 jin. All rights reserved.
//

import UIKit
// 线结构体,为了和之前的区分,这里的名字有点长
struct LineBezierPath {
    let color:UIColor
    var points:UIBezierPath
}
// 画板类,这个使用BezierPath画
class DrawBoardBezierPath: UIView {
    var lines:[LineBezierPath] = []
    // 当前选择的颜色
    var lineColor:UIColor = UIColor.blackColor()
    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
        let touch = (touches as NSSet).anyObject()
        // 初始化 UIBezierPath 对象
        let bezierPath = UIBezierPath()
        // 设置线的开始点
        bezierPath.moveToPoint((touch?.locationInView(touch?.view))!)
        // 初始化线的结构体
        let line = LineBezierPath(color: self.lineColor, points: bezierPath)
        // 添加线到线集合
        self.lines.append(line)
    }
    override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) {
        let touch = (touches as NSSet).anyObject()
        // 给当前的线添加点
        self.lines.last?.points.addLineToPoint((touch?.locationInView(touch?.view))!)
        self.setNeedsDisplay()
    }
    override func drawRect(rect: CGRect) {
        // 画
        for var i = 0;i < self.lines.count;i++
        {
            self.lines[i].points.lineCapStyle = CGLineCap.Round
            self.lines[i].points.lineJoinStyle = CGLineJoin.Round
            self.lines[i].points.lineWidth = 10
            self.lines[i].color.set()
            self.lines[i].points.stroke()
        }
    }
    // 回退
    func back()
    {
        if self.lines.count > 0
        {
            self.lines.removeLast()
            self.setNeedsDisplay()
        }
    }
    // 清屏
    func clear()
    {
        self.lines = []
        self.setNeedsDisplay()
    }
    // 保存颜色
    func save()
    {
        // 开始位图上下文
        UIGraphicsBeginImageContextWithOptions(self.bounds.size, false, 0)
        // 画图
        self.setNeedsDisplay()
        // 获取当前图片
        let context = UIGraphicsGetCurrentContext()
        self.layer.renderInContext(context!)
        let image = UIGraphicsGetImageFromCurrentImageContext()
        // 转换成 NSData 数据
        let resImage = UIImagePNGRepresentation(image)
        // 保存
        resImage?.writeToFile("/Users/admin/Desktop/DrawingBoard.png", atomically: true)
    }
    //
    func selectColor(color:UIColor)
    {
        self.lineColor = color
    }
}

触摸事件初步使用

//
//  ViewController.swift
//  触摸事件
//
//  Created by admin on 16/1/25.
//  Copyright © 2016年 jin. All rights reserved.
//

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }
    // 触摸开始
    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
        // 获取touch对象
        let touch = (touches as NSSet).anyObject()
        // 获取当前点击的位置,位置坐标是相对于当前传入的view,如果传入nil就是想对于整个窗口
        print(touch!.locationInView(touch!.view))
        // 获取连续点击的次数
        print(touch!.tapCount)
    }
    // 触摸移动
    override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) {
        let touch = (touches as NSSet).anyObject()
        print("移动前的坐标\(touch?.previousLocationInView(touch?.view))")
        print("移动后的坐标\(touch?.locationInView(touch?.view))")
        print("==============")
        // 拖动view的时候改变view的位置
        let point = ((touch?.view)! as UIView).center
        ((touch?.view)! as UIView).center = CGPointMake(point.x + ((touch?.locationInView(touch?.view).x)! - (touch?.previousLocationInView(touch?.view).x)!), point.y + ((touch?.locationInView(touch?.view).y)! - (touch?.previousLocationInView(touch?.view).y)!))
    }
    // 触摸结束
    override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {

    }
    // 终止触摸,譬如被打电话提前结束
    override func touchesCancelled(touches: Set<UITouch>?, withEvent event: UIEvent?) {

    }
    override func touchesEstimatedPropertiesUpdated(touches: Set<NSObject>) {

    }
}

swift版本手势解锁

这个很有意思啊

控制器部分
//
//  ViewController.swift
//  手势解锁
//
//  Created by admin on 16/1/25.
//  Copyright © 2016年 jin. All rights reserved.
//

import UIKit

class ViewController: UIViewController,Gesturedelegate {

    override func viewDidLoad() {
        super.viewDidLoad()
        // 初始化自定义类
        let gesture = Gesture(frame: CGRectMake(0, 0, UIScreen.mainScreen().bounds.size.width, 400))
        //
        gesture.backgroundColor = UIColor.clearColor()
        gesture.passwordDelegate = self
        self.view.backgroundColor = UIColor(patternImage: UIImage(imageLiteral: "Home_refresh_bg"))
        self.view.addSubview(gesture)
        // Do any additional setup after loading the view, typically from a nib.
    }
    func gestureCheckPassword(password: String) {
        if password == "0123"
        {
            let alert = UIAlertController(title: "登录成功", message: "登录成功", preferredStyle: UIAlertControllerStyle.Alert)
            alert.addAction(UIAlertAction(title: "确认", style: UIAlertActionStyle.Cancel, handler: nil))
            self.presentViewController(alert, animated: true, completion: nil)
            // 用下面这个弹窗会有警告
            //let alert = UIAlertView(title: "登录成功", message: "登录成功", delegate: nil, cancelButtonTitle: "登录成功")
        }
    }
}
自定义类,解锁类,其实更多的是画图
//
//  Gesture.swift
//  手势解锁
//
//  Created by admin on 16/1/25.
//  Copyright © 2016年 jin. All rights reserved.
//

import UIKit
@objc protocol Gesturedelegate
{
    optional func gestureCheckPassword(password:String)
}
class Gesture: UIView {
    lazy var buttons:[UIButton] = []// 存放所有按钮
    lazy var selectedButtons:[UIButton] = []// 存放以及选择的按钮
    lazy var point:CGPoint = CGPoint(x: 0, y: 0)// 存放当前的点击的位置
    weak var passwordDelegate:Gesturedelegate!// 验证密码的代理
    override init(frame: CGRect) {
        super.init(frame: frame)
        // 添加按钮
        for var i = 0;i < 9;i++
        {
            let button = UIButton()
            // 禁止交互,不禁止的话划过的时候会改变样式
            button.userInteractionEnabled = false
            // 设置tag,用来组合密码
            button.tag = i
            self.buttons.append(button)
            self.addSubview(button)
        }
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    // 设置按钮的布局
    override func layoutSubviews() {
        // 获得不同状态的图片
        let normalImage = UIImage(imageLiteral: "gesture_node_normal")
        let selectedImage = UIImage(imageLiteral: "gesture_node_highlighted")
        // 按钮的行数
        let colunm = 3
        // 根据行数计算边距
        let margin = (self.frame.size.width - (normalImage.size.width * CGFloat(colunm))) / CGFloat(colunm + 1)
        // 计算边距,利用取余和除
        for var i = 0;i < self.buttons.count;i++
        {
            let button = self.buttons[i]
            let marginLeft = CGFloat(i % colunm)
            let marginTop = CGFloat(i / colunm)
            let buttonRect = CGRectMake((marginLeft * normalImage.size.width) + (marginLeft + 1) * margin, ((marginTop + 1) * margin) + ((marginTop) * normalImage.size.height), normalImage.size.width, normalImage.size.height)
            button.frame = buttonRect
            button.setImage(normalImage, forState: UIControlState.Normal)
            button.setImage(selectedImage, forState: UIControlState.Selected)
            self.addSubview(button)
        }
    }
    // 开始点击的时候
    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
        self.touchesMoved(touches, withEvent: event)
    }
    // 设置当前连线状态
    override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) {
        // 获取当前touch对象
        let touch = (touches as NSSet).anyObject()
        // 获取当前触摸位置
        let location:CGPoint = (touch?.locationInView(touch?.view))!
        // 循环所有的按钮
        for var i = 0;i < self.buttons.count;i++
        {
            let button = self.buttons[i]
            // 当触摸在按钮上时,设置按钮的状态,并加入类属性,注意这里的函数
            if CGRectContainsPoint(button.frame, location) && button.selected == false
            {
                button.selected = true
                self.selectedButtons.append(button)
            }
        }
        // 追加当前触摸位置点
        self.point = location
        self.setNeedsDisplay()
    }
    // 结束触摸时做处理
    override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
        // 循环取消以选中的按钮状态
        self.selectedButtons.forEach({$0.selected = false})
        // 删除已经记录的所有已选中的按钮
        self.selectedButtons.removeAll()
        self.setNeedsDisplay()
    }
    // 画当前连线状态
    override func drawRect(rect: CGRect) {
        // 设置path对象
        let lines:UIBezierPath = UIBezierPath()
        // 如果没有选中则直接返回
        if self.selectedButtons.count == 0
        {
            return
        }
        // 设置起点
        lines.moveToPoint((self.selectedButtons.first?.center)!)
        // 初始化密码字符串
        var password = ""
        // 获取当前选中的按钮的点和tag
        selectedButtons.forEach({
            button in
            lines.addLineToPoint(button.center)
            password += "\(button.tag)"
        })
        // 添加当前触摸的点
        lines.addLineToPoint(self.point)
        // 设置线的格式
        lines.lineCapStyle = CGLineCap.Round
        lines.lineJoinStyle = CGLineJoin.Round
        lines.lineWidth = 10
        let lineColor = UIColor.blueColor()
        lineColor.set()
        // 画
        lines.stroke()
        // 执行密码的代理方法
        self.passwordDelegate?.gestureCheckPassword?(password)
    }
}