Objective-C: touchesの指しているCGPoint
タッチした場所に画像を表示したいのに表示されないという場合に考えうる対処法のひとつです。結構凡ミスなんですけど小一時間悩んだので残しておきます。
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { CGPoint theLocation = [[touches anyObject] locationInView:self.view.window]; NSLog(@"touchesBegan: (x, y) = (%.0f, %.0f)", theLocation.x, theLocation.y); UIImageView* hoge = [[UIImageView alloc] init]; hoge.image = [UIImage imageNamed:@"hoge.png"]; hoge.frame = CGRectMake(theLocation.x, theLocationY, 100, 100); [fugaView addSubview:hoge]; }
こんな感じにタッチポイントを取得してるのに、画像が表示される場所が違ってました。理由は結構簡単で
CGPoint theLocation = [[touches anyObject] locationInView:self.view.window];
ここで参照しているViewの指定がself.view.windowになってたからでした。
CGPoint theLocation = [[touches anyObject] locationInView:fugaView];
これで解決。addするViewと参照するViewを合わせていないだけでした。