UIButton TouchUpInside触摸位置

And*_*rew 31 iphone touch uibutton uitouch sender

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

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

和各种其他迭代.按钮的目标方法通过以下方式从中获取信息sender:

    UIButton *button = sender;
Run Code Online (Sandbox Code Playgroud)

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

我在网上看了找不到类似的东西,所以提前谢谢.

Cal*_*leb 59

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

这是正确的想法,除了这个代码可能在你的视图控制器中的一个动作内,对吧?如果是,则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);
}
Run Code Online (Sandbox Code Playgroud)


Amm*_*eeb 5

对于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)")  
}
Run Code Online (Sandbox Code Playgroud)