UIButton TouchUpInside 触摸位置

35

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

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的东西?

我在网上搜索了一下,没有找到类似的内容,提前感谢。


没有touchUpLocation,UIButton是一个控件,你无法获取UIButton点击的位置。http://developer.apple.com/library/ios/#DOCUMENTATION/UIKit/Reference/UIButton_Class/UIButton/UIButton.html - Praveen-K
1
我不是字面上的意思是touchUpLocation,我是指类似的东西。 - Andrew
3
@Praveen-K,那是不正确的。UIKit支持带有第二个参数UIEvent的操作,该操作触发了事件。从中,您可以获取触摸列表,每个触摸都有一个位置。请参阅我下面发布的代码。但是,确实没有返回上次点击位置的UIButton方法。 - Caleb
2个回答

61
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
有没有办法从“-(IBAction)buttonPressed:(id)sender”中获取事件...?(也就是说,我有一个庞大的项目,我想瓶颈这个,而不必将所有按钮更改为“...forEvent:”,如果可以的话。)谢谢! - Olie
据我所知,如果您想要事件,您需要更改操作的签名以包括事件参数。 - Caleb
但是如果您有多个触摸,这并不能让您更进一步。 - Peter Lapisu
显示剩余2条评论

7

对于Swift 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)")  
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接