はりまや日記

なんか適当にいろいろ綴ったりなんかするところ

iphoneアプリ開発日記その11

webview の座標を取ってみる

webview にポップアップを出したくなったので、タッチしたところの座標が必要なのです。

タッチイベントの検知は前回やったので、あとは座標を取ればいいだけかな。
ひゃっはーこいつは楽勝だぜ!


いったいどうやって座標を取れというのです?

グーグル先生にお尋ねしたところ、3つ候補が返ってきた

  1. ios の GestureRecognizer で取得する
  2. ios の touchesBegan メソッドで取得する
  3. javascript で取得する

なんとなくジェスチャーは使いたくないので、2か3だな。
ひとまず両方やってみよう。


touchesBegan で座標を取る

さて、試してみよう。
単純に touchesBegan メソッドを実装すればいいのかと思ったら、webview の場合はそのままでは動かないようだ。
いろいろ見ていたところ、カテゴリを使ってイベントを渡してあげるといいみたい。
ここを参考にした。

んで、コードがこうなった。
後で使う為に、touchesBegan 内で座標をプロパティに突っ込んでおく。

コード

UIScrollView+TouchEvent.h

#import <UIKit/UIKit.h>

@interface UIScrollView (TouchEvent)

@end


UIScrollView+TouchEvent.m

#import "UIScrollView+TouchEvent.h"

@implementation UIScrollView (TouchEvent)

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [[self nextResponder] touchesBegan:touches withEvent:event];
}

@end

viewController.m

@interface ViewController ()
@property CGPoint touchPoint;
@end

@implementation ViewController
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    self.touchPoint = [[touches anyObject] locationInView:self.view];
    NSLog(@"point: %f, %f", self.touchPoint.x, self.touchPoint.y);
    [super touchesBegan:touches withEvent:event];
}
@end

結果 ちゃんと座標が取れました。

2013-06-25 11:48:33.319 webTest[80946:11303] point: 171.000000, 145.000000

OK っすね


javascript で座標を取る


前回、タッチイベントを扱ったのですが、
それに「pageX/pageY」というプロパティがありました。
これを使えばいけるだろうか…

ためしてみましょう。


コード

  $('body').bind("touchstart",
                 function()
                 {
                 event.preventDefault;
                 alert("pageX:"+event.pageX+" pageY: " + event.pageY);
                 });

結果
iphone シミュレータの高さは450 程度なのに、普通に pageY に 700 とかくる。
pageX/pageY は、やはりページ全体の座標だった。


さて、どうするか。
ここを見ると、clientX/clientY プロパティが使えそうだ。
しかし、touchevent には含まれていないようだ。

調べてみると、event.changedTouches[0] の中に入ってるみたい。
iPhone/Android/PC 対応。jQuery で書くタッチイベント (フェンリル | デベロッパーズブログ)

試してみる


コード

$(function()
  {
  var bodyInterval = 300;
  $('body').bind("touchstart",
                 function()
                 {
                 event.preventDefault;
                 
                 var x = event.changedTouches[0].clientX;
                 var y = event.changedTouches[0].clientY;
                 
                 timer = setTimeout(function(){
                                    alert("x:"+x+" y: " +y);
                                    }, bodyInterval);
                 });
  
  $('body').bind("touchend touchmove touchcancel",
                 function(){ clearTimeout(timer) ;
                 });
});

結果
タッチしたのは両方とも左上らへんです。

スクロール前
f:id:harrymaya:20130625141918p:plain

スクロール後
f:id:harrymaya:20130625141924p:plain


これで、ページのスクロールに関係なく、画面上の座標が取得できました。