輕掃手勢(shì)識(shí)別UISwipeGestureRecognizer
以下創(chuàng)建手勢(shì)將會(huì)添加到gestureView上
//將view的背景顏色設(shè)置為白色
self.view.backgroundColor = UIColor.white
//創(chuàng)建一個(gè)UIView
let gestureView = UIView(frame: CGRect(x: 0, y: 100, width:
308, height: 308))
gestureView.backgroundColor = UIColor.green
self.view.addSubview(gestureView)
創(chuàng)建輕掃手勢(shì)
let swipe = UISwipeGestureRecognizer(target: self, action: #selector(swipeAction))
設(shè)置手勢(shì)支持的輕掃方向矫钓,而且一個(gè)輕掃手勢(shì)只能存儲(chǔ)一個(gè)方向
swipe.direction = .right
let swipe2 = UISwipeGestureRecognizer(target: self, action: #selector(swipeAction))
swipe.direction = .left
把輕掃手勢(shì)添加到gestureView上
gestureView.addGestureRecognizer(swipe)
gestureView.addGestureRecognizer(swipe2)
實(shí)現(xiàn)輕掃手勢(shì)關(guān)聯(lián)方法swipeAction
//MARK:- 輕掃手勢(shì)關(guān)聯(lián)方法
func swipeAction(sender:UISwipeGestureRecognizer){
if sender.direction == .right{
sender.view?.backgroundColor = backRandomColor()
}
else if sender.direction == .left {
sender.view?.superview?.backgroundColor = backRandomColor()
}
}
定義一個(gè)backRandomColor方法用來(lái)隨機(jī)變換背景顏色
func backRandomColor()->UIColor {
//產(chǎn)生0~1的隨機(jī)數(shù)
let redView = Float(arc4random_uniform(256))/255.0
let greenView = Float(arc4random_uniform(256))/255.0
let blueView = Float(arc4random_uniform(256))/255.0
//產(chǎn)生隨機(jī)顏色
let color = UIColor(red: CGFloat(redView), green: CGFloat(greenView), blue: CGFloat(blueView), alpha: 1.0)
return color
}