您的第一个链接是 using PhoneGap.Gesture
,据我所知,它在 0.8 中不存在(至少对于 iphone 而言)。这是一篇相当新的帖子,但可能是最近添加的?我没有使用任何高于 0.8 的版本
我通过“扩展”phonegap 为 phonegap 应用程序添加了摇动手势支持,如下所示。但首先是一个警告:
Apple 认为 PhoneGap 0.8 可以提交到应用商店。由于这本质上是对 PhoneGap 0.8 的扩展(尽管非常简单),因此可能存在被拒绝的风险。我为此开发的应用程序尚未通过审批程序,因此我无法就此提供任何进一步的建议。
另请注意,由于使用了新UIEventSubtypeMotionShake
API ,这仅适用于 OS 3.0+
此外,这是特定于 iPhone 的。如果您想要 PhoneGap 的跨平台功能,除非您愿意在其他平台(android 等)上实现本机端修改,否则此答案可能不适合您。在这种情况下,最好等待 iphone 上支持此功能的官方 phonegap 版本。
将以下代码添加到 PhoneGapViewController.m
- (void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event
{
if (UIEventSubtypeMotionShake == motion)
{
[webView stringByEvaluatingJavaScriptFromString:@"navigator.myext.onShakeGesture();"];
}
}
然后将其添加为 javascript 模块myext.js
/* We need PhoneGap.js to be loaded to work properly before we can initialise so wait for it here */
(function()
{
var timer = setInterval(function()
{
if (typeof(PhoneGap == 'object'))
{
clearInterval(timer);
myExtInit();
}
}, 1);
})();
function MyExt()
{
// initialization
this.callbacks = {
onShakeGesture: []
};
}
/* Called by ObjectiveC side when a shake gesture is detected */
MyExt.prototype.onShakeGesture = function()
{
for (var i = 0; i < this.callbacks.onShakeGesture.length; i++)
{
var f = this.callbacks.onShakeGesture[i];
f();
}
};
MyExt.prototype.addShakeGestureListener = function(shakeCallback)
{
if (typeof(shakeCallback) == 'function')
{
this.callbacks.onShakeGesture.push(shakeCallback)
}
};
function myExtInit()
{
// Init phonegap extension specific objects using PhoneGap.addConstructor
PhoneGap.addConstructor(function() {
if (typeof navigator.myext == "undefined") navigator.myext = new MyExt();
});
}
现在将 myext.js 包含在您的 HTML 内容<head>
部分中,就在链接之后phonegap.js
<script type="text/javascript" charset="utf-8" src="myext.js"/>
并从脚本中使用(示例会导致警报,但请执行您需要做的事情):
function watchShake() {
var cb = function(){
navigator.notification.alert("Shake it!");
};
navigator.myext.addShakeGestureListener(cb);
}