每次打開網易郵箱大師進來第一個界面就是解鎖削彬,這種設計很好的保護用戶的隱私宴抚。手勢解鎖也是一種很好的密碼方式,今天小編就介紹一下這個手勢解鎖奠蹬。
先看下效果,我在網易郵箱大師的bandle里沒有找到解鎖相關的圖片嗡午,感覺有可能是自己畫的囤躁,這里我的圖片是東湊西湊的,大家湊合看吧荔睹。
思路
創(chuàng)建按鈕
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)
}
}
設置起點和按鈕選中狀態(tài)
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
方法主要是繪制軌跡和設置按鈕狀態(tài)
// 繪制軌跡
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消玄。