繁体   English   中英

UIButton TouchUpInside触摸位置

[英]UIButton TouchUpInside Touch Location

所以我有一个大的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

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

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

对于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