在 iOS 中做一个摩擦屏幕的手势?
Posted
技术标签:
【中文标题】在 iOS 中做一个摩擦屏幕的手势?【英文标题】:Making a rubbing screen gesture in iOS? 【发布时间】:2014-10-05 16:21:55 【问题描述】:基本上,我想使用自定义手势制作手机游戏。手势有点像从左到右,从右到左摩擦屏幕。
如果手势从左向右移动,这将调用一个方法并添加一个点。并且一旦手势从右向左摩擦,用户也可以获得一分。
但问题是,当我使用 Swipe 手势识别器时,我必须将手指从屏幕上松开,才能调用该方法。如果我只是做摩擦手势,我无法调用该方法来加分。
相反,我尝试使用 touchesBegan、touchesMoved 方法来检测手指的位置。但是,touchesMoved 会创建许多点来与起始点进行比较,这会导致调用方法多次而不是一次。
override func touchesBegan(touches: NSSet, withEvent event: UIEvent)
for touch: AnyObject in touches
self.touchStartPoint = touch.locationInView(self.myView).x
override func touchesMoved(touches: NSSet, withEvent event: UIEvent)
for touch: AnyObject in touches
self.touchOffsetPoint = touch.locationInView(self.myView).x - touchStartPoint
if tempTouchOffsetPoint < touchOffsetPoint
var xValueIncreaseArray: NSMutableArray = []
xValueIncreaseArray.addObject(touchOffsetPoint)
var maxValue: Double = (xValueIncreaseArray as AnyObject).valueForKeyPath("@max.self") as Double
println("\(maxValue)")
if maxValue - Double (self.touchStartPoint) > 50
println("right")
println("right")
else if tempTouchOffsetPoint > touchOffsetPoint
/* var xValueDecreaseArray: NSMutableArray = []
xValueDecreaseArray.addObject(touchOffsetPoint)*/
println("left")
else if tempTouchOffsetPoint == touchOffsetPoint
println("Remain")
tempTouchOffsetPoint = touchOffsetPoint
有什么方法可以检测到摩擦手势吗?并且每次手指转动方向时,它只会调用一次方法为用户添加分数?非常感谢!
【问题讨论】:
我相信您正在寻找一个 UIPanGestureRecognizer,它会在手指移动时为您提供新的更新(但是,您必须计算方向)。 恐怕 UIPanGestureRecognizer 不能只调用一次。我试过了,它会被调用很多次。 【参考方案1】:这对我有用:
let deadZone:CGFloat = 10.0
var previousTouchPoint: CGFloat!
var isMovingLeft:Bool? = nil
override func touchesMoved(touches: NSSet, withEvent event: UIEvent)
let point = touches.anyObject()?.locationInView(self)
if let newPoint = point?.x
if previousTouchPoint == nil
println("Started")
previousTouchPoint = newPoint
else
// Check if they have moved beyond the dead zone
if (newPoint < (previousTouchPoint - deadZone)) || (newPoint > (previousTouchPoint + deadZone))
let newDirectionIsLeft = newPoint < previousTouchPoint
// Check if the direction has changed
if isMovingLeft != nil && newDirectionIsLeft != isMovingLeft!
println("Direction Changed: Point")
println((newDirectionIsLeft) ? "Moving Left" : "Moving Right")
isMovingLeft = newDirectionIsLeft
previousTouchPoint = newPoint
override func touchesCancelled(touches: NSSet!, withEvent event: UIEvent!)
previousTouchPoint = nil
isMovingLeft = nil
override func touchesEnded(touches: NSSet, withEvent event: UIEvent)
previousTouchPoint = nil
isMovingLeft = nil
【讨论】:
以上是关于在 iOS 中做一个摩擦屏幕的手势?的主要内容,如果未能解决你的问题,请参考以下文章
在 MPMoviePlayerController 上执行捏合手势时屏幕黑屏