UIButton TouchUpInside Touch Location
So I have a large UIButton
, it is a UIButtonTypeCustom
, and the button targe开发者_运维问答t is called for UIControlEventTouchUpInside
. My question is how can I determine where in the UIButton
the touch occured. 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
:
UIButton *button = sender;
So is there any way I could use something like: 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. You should be passing a pointer to the button into -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:
@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)")
}
精彩评论