每次打开网易邮箱大师进来第一个界面就是解锁,这种设计很好的保护用户的隐私。手势解锁也是一种很好的密码方式,今天小编就介绍一下这个手势解锁。
先看下效果,我在网易邮箱大师的bandle里没有找到解锁相关的图片,感觉有可能是自己画的,这里我的图片是东凑西凑的,大家凑合看吧。
思路
创建按钮
func initButtons() {
let btnW: CGFloat = 80
let rowCount: CGFloat = 3
let gap = (self.frame.width - btnW * rowCount) / (rowCount + 1)
for i in 0 ..< 9 {
let list = CGFloat(i % 3 ) // 列
let row = CGFloat( i / 3 ) // 行
let button = UIButton()
button.frame = CGRectMake((btnW + gap) * list + gap, (btnW + gap) * row + 20 + topLabel.frame.maxY , btnW, btnW)
button.tag = i
button.setBackgroundImage(UIImage(named: "handle_normal"), forState: .Normal)
button.setBackgroundImage(UIImage(named: "handle_selected"), forState: .Selected)
button.userInteractionEnabled = false
self.addSubview(button)
}
}
设置起点和按钮选中状态
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
guard result else {
return
}
let point = pointWithTouch(touches)
if let btn = buttonWithPoint(point) {
if !btn.selected {
btn.selected = true
buttons.append(btn)
}
}
}
移动中添加轨迹上的按钮到数组,并且不能重复添加,最后调用self.setNeedsDisplay()
绘制轨迹
override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) {
guard result else {
return
}
let point = pointWithTouch(touches)
movePoint = point
if let btn = buttonWithPoint(point) {
if !btn.selected {
btn.selected = true
if !buttons.contains(btn) {
buttons.append(btn)
}
}
}
self.setNeedsDisplay()
}
结束后记录按钮的顺序,并保存到本地,最后清空数组重新绘制一下
override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
guard result else {
return
}
var str = ""
for button in buttons {
button.selected = false
str += String(button.tag)
}
if handleResult(str) {
result = true
buttons.removeAll()
self.setNeedsDisplay()
handleBlock?(result: true)
}else {
for button in buttons {
button.setBackgroundImage(UIImage(named: "handle_warning"), forState: .Normal)
}
result = false
self.setNeedsDisplay()
addAnimation()
dispatch_after(dispatch_time(DISPATCH_TIME_NOW,
Int64(2.0 * Double(NSEC_PER_SEC))), dispatch_get_main_queue()) { () -> Void in
self.result = true
for button in self.buttons {
button.setBackgroundImage(UIImage(named: "handle_normal"), forState: .Normal)
}
self.buttons.removeAll()
self.setNeedsDisplay()
}
handleBlock?(result: false)
}
}
drawRect
方法主要是绘制轨迹和设置按钮状态
// 绘制轨迹
override func drawRect(rect: CGRect) {
if self.buttons.count == 0 {
return
}
let path = UIBezierPath()
for i in 0 ..< self.buttons.count {
let button = buttons[i]
if i == 0 {
path.moveToPoint(button.center)
}else {
path.addLineToPoint(button.center)
}
}
path.addLineToPoint(movePoint)
path.lineWidth = 8
if result {
UIColor.greenColor().set()
}else {
UIColor.redColor().set()
}
path.lineJoinStyle = .Round
path.stroke()
}
以上是主要代码,欢迎大家指出错误
在这里下载代码,欢迎大家Star。