问题描述
我正在使用加速计在UIScrollVIew中滚动多个子视图。当用户向右轻拂iPhone时,我希望视图(纵向)向右滚动,当向左轻拂设备时,我希望向左滚动。
I am using the accelerometer to scroll multiple subViews in a UIScrollVIew. I want the view (portrait orientation) to scroll to the right when the user flicks the iPhone to the right, and scroll to the left when the device is flicked to the left.
我认为我只能通过记录正x或负x加速度值来做到这一点,但我发现这些值通常是正值和负值的混合。我已将地板设置为1.5g以消除无抖动,并且在0.5秒的持续时间内查看x值。
I thought I could do that just by noting positive or negative x acceleration values, but I see that the values are usually a mixture of positive and negative values. I have set the floor at 1.5g to eliminate non-shake movement, and am looking at the x values over the duration of .5 seconds.
我确信有一种三角测量方法可以确定轻弹的整体方向,并且你必须在轻弹动作的持续时间内测量数值。我也确定有人已经知道了这个。
I'm sure there is a trigonometrical method for determining the overall direction of a flick, and that you have to measure values over the duration of the flick motion. I'm also sure that someone has already figured this one out.
那里有任何想法吗?
谢谢
推荐答案
我开发了一个解决方案,它给出了比建议的解决方案更好的反馈(仅适用于左右摇动)。
我在这里做的方式非常敏感(识别一个小的震动),但可以通过改变tresholdFirstMove和tresholdBackMove(增加灵敏度较低)来调整灵敏度
I developed a solution which gives me better feedback than the proposed solution (only for left and right shake).The way I did it here is quite sensitive (recognizes a small shake), but sensitivity can be adapted by changing tresholdFirstMove and tresholdBackMove (increase for lower sensitivity)
在Swift中:
(在你的viewController中。并添加import CoreMotion)
In Swift :(in your viewController. And add "import CoreMotion")
var startedLeftTilt = false
var startedRightTilt = false
var dateLastShake = NSDate(timeIntervalSinceNow: -2)
var dateStartedTilt = NSDate(timeIntervalSinceNow: -2)
var motionManager = CMMotionManager()
let tresholdFirstMove = 3.0
let tresholdBackMove = 0.5
override func viewDidLoad() {
// your code
motionManager.gyroUpdateInterval = 0.01
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
motionManager.startGyroUpdatesToQueue(NSOperationQueue.currentQueue(), withHandler: { (gyroData, error) -> Void in
self.handleGyroData(gyroData.rotationRate)
})
}
private func handleGyroData(rotation: CMRotationRate) {
if fabs(rotation.z) > tresholdFirstMove && fabs(dateLastShake.timeIntervalSinceNow) > 0.3
{
if !startedRightTilt && !startedLeftTilt
{
dateStartedTilt = NSDate()
if (rotation.z > 0)
{
startedLeftTilt = true
startedRightTilt = false
}
else
{
startedRightTilt = true
startedLeftTilt = false
}
}
}
if fabs(dateStartedTilt.timeIntervalSinceNow) >= 0.3
{
startedRightTilt = false
startedLeftTilt = false
}
else
{
if (fabs(rotation.z) > tresholdBackMove)
{
if startedLeftTilt && rotation.z < 0
{
dateLastShake = NSDate()
startedRightTilt = false
startedLeftTilt = false
println("\\\n Shaked left\n/")
}
else if startedRightTilt && rotation.z > 0
{
dateLastShake = NSDate()
startedRightTilt = false
startedLeftTilt = false
println("\\\n Shaked right\n/")
}
}
}
}
这篇关于如何确定iPhone震动的方向的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!