简体   繁体   English

UIButton TouchUpInside触摸位置

[英]UIButton TouchUpInside Touch Location

So I have a large UIButton , it is a UIButtonTypeCustom , and the button target is called for UIControlEventTouchUpInside . 所以我有一个大的UIButton ,它是一个UIButtonTypeCustom ,并且为UIControlEventTouchUpInside调用了按钮目标。 My question is how can I determine where in the UIButton the touch occured. 我的问题是如何确定触摸发生在UIButton的位置。 I want this info so I can display a popup from the touch location. 我想要这个信息,所以我可以从触摸位置显示一个弹出窗口。 Here is what I've tried: 这是我尝试过的:

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

and various other iterations. 和各种其他迭代。 The button's target method get info from it via the sender : 按钮的目标方法通过sender从中获取信息:

    UIButton *button = sender;

So is there any way I could use something like: button.touchUpLocation ? 那么有什么方法可以使用像: button.touchUpLocation

I looked online and couldn't find anything similar to this so thanks in advance. 我在网上看了找不到类似的东西,所以提前谢谢。

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

That's the right idea, except that this code is probably inside an action in your view controller, right? 这是正确的想法,除了这个代码可能在你的视图控制器中的一个动作内,对吧? If so, then self refers to the view controller and not the button. 如果是这样,那么self指的是视图控制器而不是按钮。 You should be passing a pointer to the button into -locationInView: . 您应该将指向该按钮的指针传递给-locationInView: .

Here's a tested action that you can try in your view controller: 以下是您可以在视图控制器中尝试的经过测试的操作:

- (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);
}

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM