2011-09-10 168 views
28

所以我有一个大的UIButton,这是一个UIButtonTypeCustom,并且按钮目标被称为UIControlEventTouchUpInside。我的问题是如何确定触摸发生在UIButton的哪个位置。我想要这个信息,所以我可以从触摸位置显示一个弹出窗口。这是我试过的:UIButton TouchUpInside触摸位置

UITouch *theTouch = [touches anyObject]; 
CGPoint where = [theTouch locationInView:self]; 
NSLog(@" touch at (%3.2f, %3.2f)", where.x, where.y); 

和各种其他迭代。按钮的目标方法通过sender从它那里得到信息:

UIButton *button = sender; 

那么,有没有办法,我可以使用类似:button.touchUpLocation

我在网上看,找不到类似这样的事情,所以在此先感谢。

+0

没有touchUpLocation,UIButton的是你不能得到控制UIButton点击的位置。 http://developer.apple.com/library/ios/#DOCUMENTATION/UIKit/Reference/UIButton_Class/UIButton/UIButton.html –

+1

我的意思不是字面上touchUpLocation,我的意思是这样的 – Andrew

+2

@ Praveen-K,这是不正确的。 UIKit支持采取第二个参数的动作,即触发动作的UIEvent。从中你可以得到触摸列表,每个触摸都有一个位置。看到我在下面发布的代码。但是,UIButton确实没有返回最后点击位置的方法。 – Caleb

回答

56
UITouch *theTouch = [touches anyObject]; 
CGPoint where = [theTouch locationInView:self]; 
NSLog(@" touch at (%3.2f, %3.2f)", where.x, where.y); 

这是正确的想法,除了这个代码可能在你的视图控制器中的一个动作,对吧?如果是这样,则self引用视图控制器而不是按钮。您应该将一个指针指向-locationInView:

这里有一个测试的动作,你可以在你的视图控制器尝试:

- (IBAction)buttonPressed:(id)sender forEvent:(UIEvent*)event 
{ 
    UIView *button = (UIView *)sender; 
    UITouch *touch = [[event touchesForView:button] anyObject]; 
    CGPoint location = [touch locationInView:button]; 
    NSLog(@"Location in button: %f, %f", location.x, location.y); 
} 
+1

谢谢,这完全解决了我的问题。我认为这是无法完成的,所以这很好。 – Andrew

+1

什么是一个伟大的代码片段 - 有时这些事情会显示出来,这再次确认了你对人性的信仰:-) – SomaMan

+0

有没有办法从' - (IBAction)buttonPressed:(id)sender' ...? (也就是说,我有一个巨大的项目,如果可以的话,我想瓶颈这个,而不必将所有按钮都改为'... forEvent:')。谢谢! – Olie

0

您是否尝试添加手势识别器到您的按钮?

+0

我没有这样做,因为在我过去使用手势识别器的经验中,他们不适用于子视图。我确定我做错了。但它似乎不是一种姿态。我想知道按钮何时被按下,而不是当视图被点击时。但谢谢你的回答 – Andrew

+0

@ Jean-Denis Muys这个答案应该是一个评论,除非你打算提供你的建议的细节。此外,我认为在这种情况下,最佳答案更合适,但添加手势识别器应该与解决方案一样紧密。正确设置它们应该与使用事件一样工作。另外 –

4

对于雨燕3.0:

@IBAction func buyTap(_ sender: Any, forEvent event: UIEvent) 
{ 
     let myButton:UIButton = sender as! UIButton 
     let touches: Set<UITouch>? = event.touches(for: myButton) 
     let touch: UITouch? = touches?.first 
     let touchPoint: CGPoint? = touch?.location(in: myButton) 
     print("touchPoint\(touchPoint)") 
}