Rectangle 27 1

I've managed to resolve this. Problem was the auto layout constraints. I have no idea why they would stop the touches event. I removed all constraints and reset them.

ios - UIView not receiving touch events but view below it are - Stack ...

ios objective-c uiview
Rectangle 27 41

By setting userInteractionEnabled to NO for your scroll view, the view controller will start receiving touch events since UIViewController is a subclass of UIResponder. You can override one or more of these methods in your view controller to respond to these touches:

class ViewController: UIViewController {
    @IBOutlet weak var scrollView: UIScrollView!

    // This array keeps track of all obstacle views
    var obstacleViews : [UIView] = []

    override func viewDidLoad() {
        super.viewDidLoad()

        // Create an obstacle view and add it to the scroll view for testing purposes
        let obstacleView = UIView(frame: CGRectMake(100,100,100,100))
        obstacleView.backgroundColor = UIColor.redColor()
        scrollView.addSubview(obstacleView)

        // Add the obstacle view to the array
        obstacleViews += obstacleView
    }

    override func touchesBegan(touches: NSSet!, withEvent event: UIEvent!) {
        testTouches(touches)
    }

    override func touchesMoved(touches: NSSet!, withEvent event: UIEvent!) {
        testTouches(touches)
    }

    func testTouches(touches: NSSet!) {
        // Get the first touch and its location in this view controller's view coordinate system
        let touch = touches.allObjects[0] as UITouch
        let touchLocation = touch.locationInView(self.view)

        for obstacleView in obstacleViews {
            // Convert the location of the obstacle view to this view controller's view coordinate system
            let obstacleViewFrame = self.view.convertRect(obstacleView.frame, fromView: obstacleView.superview)

            // Check if the touch is inside the obstacle view
            if CGRectContainsPoint(obstacleViewFrame, touchLocation) {
                println("Game over!")
            }
        }
    }

}

This is a good method. However, doesn't it redefine touch whenever touchesMoved is called, which isn't necessary? Efficiency could perhaps be improved somewhat. CGRectContainsPoint is the way to go for finding the location, but you need to call it twice for the UIView on each side

Yup, it does indeed call testTouches as long as the user keeps moving his finger. But the OP will probably replace println("Game over!") by some code that replaces the current screen with a game over screen on the first contact so I don't think that's will be a problem. And you're right that CGRectContainsPoint needs to be called at least twice. But the obstacleViews array contains all the obstacle views, including the two 'critical' views so that's fine. If the performance is subpar, the OP can always optimize the code to only check the two 'critical' views or currently visible views.

Fair. All the code is here, perhaps another function could be created to check the initial touch.

can you please post an swift 3 version?

ios - Xcode & Swift - Detecting user touch of UIView inside of UIScrol...

ios xcode uiview uiscrollview swift
Rectangle 27 7

Based on your reply I feel safe concluding that your problem is that the parent view of your buttons does not contain the buttons in its interactive area. You can still see them because you are not clipping the subviews, but still you can't interact with them. There are two options to solve your problem

a) (Recommended)Place the buttons in the proper place so that they are within the visible (and interactive area of the parent view)

b) Override the hitTest selector of the parent view, so that it tracks all of touches in its subviews, including those outside of its bounds. For that you will have to create a subclass of UIView and implement the following:

-(UIView *) hitTest:(CGPoint)point withEvent:(UIEvent *)event{
UIView* result = [super hitTest:point withEvent:event];
if (result)
    return result;
for (UIView* sub in [self.subviews reverseObjectEnumerator]) {
    CGPoint pt = [self convertPoint:point toView:sub];
    result = [sub hitTest:pt withEvent:event];
    if (result)
        return result;
}
return nil;

Yes, the problem was the buttons parent view. When I set the foreground color of that view, I could only see the color in a small area, the remaining part was transparent, and only the colored part was active. I fixed the problem by deselecting every line in the autosize box in IB. Thanks!

I'm glad it works, good luck with that.

ios - My custom UIView dos not receive touches - Stack Overflow

ios uiview nib
Rectangle 27 514

In iOS 3.2 and higher, you can use gesture recognizers. For example, this is how you would handle a tap event:

//The setup code (in viewDidLoad in your view controller)
UITapGestureRecognizer *singleFingerTap = 
  [[UITapGestureRecognizer alloc] initWithTarget:self 
                                          action:@selector(handleSingleTap:)];
[self.view addGestureRecognizer:singleFingerTap];

//The event handling method
- (void)handleSingleTap:(UITapGestureRecognizer *)recognizer
{
  CGPoint location = [recognizer locationInView:[recognizer.view superview]];

  //Do stuff here...
}

There are a bunch of built in gestures as well. Check out the docs for iOS event handling and UIGestureRecognizer. I also have a bunch of sample code up on github that might help.

But that is overwriting touch defautlt action of the view. Is it possible to call default touch action of the view? Something like [super touchesBegan] ?...

What does the CGPoint line do?

@yourfriendzak the CGPoint represents the location of the tap in the superview of the tapped view. You can use this point to move the tapped view (or a sibling view) to the tapped location. This is more useful in the handler for a UIPanGestureRecognizer for dragging the view around the screen.

great concise answer, thanks. but sheesh, wouldn't it be nice if this were a wee bit easier?! :)

It's not too bad, but I wish there were a block based API like github.com/neror/ftutils/blob/master/Headers/FTUtils/. Xcode 4 does have support for adding/configuring gesture recognizers in Interface Builder, too.

ios - How to add a touch event to a UIView? - Stack Overflow

ios objective-c events uiview touch
Rectangle 27 506

In iOS 3.2 and higher, you can use gesture recognizers. For example, this is how you would handle a tap event:

//The setup code (in viewDidLoad in your view controller)
UITapGestureRecognizer *singleFingerTap = 
  [[UITapGestureRecognizer alloc] initWithTarget:self 
                                          action:@selector(handleSingleTap:)];
[self.view addGestureRecognizer:singleFingerTap];

//The event handling method
- (void)handleSingleTap:(UITapGestureRecognizer *)recognizer
{
  CGPoint location = [recognizer locationInView:[recognizer.view superview]];

  //Do stuff here...
}

There are a bunch of built in gestures as well. Check out the docs for iOS event handling and UIGestureRecognizer. I also have a bunch of sample code up on github that might help.

But that is overwriting touch defautlt action of the view. Is it possible to call default touch action of the view? Something like [super touchesBegan] ?...

What does the CGPoint line do?

@yourfriendzak the CGPoint represents the location of the tap in the superview of the tapped view. You can use this point to move the tapped view (or a sibling view) to the tapped location. This is more useful in the handler for a UIPanGestureRecognizer for dragging the view around the screen.

great concise answer, thanks. but sheesh, wouldn't it be nice if this were a wee bit easier?! :)

It's not too bad, but I wish there were a block based API like github.com/neror/ftutils/blob/master/Headers/FTUtils/. Xcode 4 does have support for adding/configuring gesture recognizers in Interface Builder, too.

Sign up for our newsletter and get our top new questions delivered to your inbox (see an example).

ios - How to add a touch event to a UIView? - Stack Overflow

ios objective-c events uiview touch
Rectangle 27 73

Adding a Gesture in the Interface Builder

There are a number of commonly used touch events (or gestures) that you can be notified of when you add a Gesture Recognizer to your view. They following gesture types are supported by default:

UITapGestureRecognizer
UILongPressGestureRecognizer
  • UIPanGestureRecognizer Pan (moving your finger across the screen)
UISwipeGestureRecognizer
  • UIPinchGestureRecognizer Pinch (moving two fingers together or apart - usually to zoom)
UIRotationGestureRecognizer

In addition to these, you can also make your own custom gesture recognizer.

Drag a gesture recognizer from the object library onto your view.

Control drag from the gesture in the Document Outline to your View Controller code in order to make an Outlet and an Action.

To add a gesture programmatically, you (1) create a gesture recognizer, (2) add it to a view, and (3) make a method that is called when the gesture is recognized.

import UIKit
class ViewController: UIViewController {

    @IBOutlet weak var myView: UIView!

    override func viewDidLoad() {
        super.viewDidLoad()

        // 1. create a gesture recognizer (tap gesture)
        let tapGesture = UITapGestureRecognizer(target: self, action: #selector(handleTap(sender:)))

        // 2. add the gesture recognizer to a view
        myView.addGestureRecognizer(tapGesture)
    }

    // 3. this method is called when a tap is recognized
    func handleTap(sender: UITapGestureRecognizer) {
        print("tap")
    }
}
  • The sender parameter is optional. If you don't need a reference to the gesture then you can leave it out. If you do so, though, remove the (_:) after the action method name when creating the gesture.
handleTap
action: #selector(someMethodName(sender:))

You can study the gesture recognizers that I added to these views to see how they work.

Here is the code for that project:

import UIKit
class ViewController: UIViewController {

    @IBOutlet weak var tapView: UIView!
    @IBOutlet weak var doubleTapView: UIView!
    @IBOutlet weak var longPressView: UIView!
    @IBOutlet weak var panView: UIView!
    @IBOutlet weak var swipeView: UIView!
    @IBOutlet weak var pinchView: UIView!
    @IBOutlet weak var rotateView: UIView!
    @IBOutlet weak var label: UILabel!

    override func viewDidLoad() {
        super.viewDidLoad()

        // Tap
        let tapGesture = UITapGestureRecognizer(target: self, action: #selector(handleTap))
        tapView.addGestureRecognizer(tapGesture)

        // Double Tap
        let doubleTapGesture = UITapGestureRecognizer(target: self, action: #selector(handleDoubleTap))
        doubleTapGesture.numberOfTapsRequired = 2
        doubleTapView.addGestureRecognizer(doubleTapGesture)

        // Long Press
        let longPressGesture = UILongPressGestureRecognizer(target: self, action: #selector(handleLongPress(gesture:)))
        longPressView.addGestureRecognizer(longPressGesture)

        // Pan
        let panGesture = UIPanGestureRecognizer(target: self, action: #selector(handlePan(gesture:)))
        panView.addGestureRecognizer(panGesture)

        // Swipe (right and left)
        let swipeRightGesture = UISwipeGestureRecognizer(target: self, action: #selector(handleSwipe(gesture:)))
        let swipeLeftGesture = UISwipeGestureRecognizer(target: self, action: #selector(handleSwipe(gesture:)))
        swipeRightGesture.direction = UISwipeGestureRecognizerDirection.right
        swipeLeftGesture.direction = UISwipeGestureRecognizerDirection.left
        swipeView.addGestureRecognizer(swipeRightGesture)
        swipeView.addGestureRecognizer(swipeLeftGesture)

        // Pinch
        let pinchGesture = UIPinchGestureRecognizer(target: self, action: #selector(handlePinch(gesture:)))
        pinchView.addGestureRecognizer(pinchGesture)

        // Rotate
        let rotateGesture = UIRotationGestureRecognizer(target: self, action: #selector(handleRotate(gesture:)))
        rotateView.addGestureRecognizer(rotateGesture)

    }

    // Tap action
    func handleTap() {
        label.text = "Tap recognized"

        // example task: change background color
        if tapView.backgroundColor == UIColor.blue {
            tapView.backgroundColor = UIColor.red
        } else {
            tapView.backgroundColor = UIColor.blue
        }

    }

    // Double tap action
    func handleDoubleTap() {
        label.text = "Double tap recognized"

        // example task: change background color
        if doubleTapView.backgroundColor == UIColor.yellow {
            doubleTapView.backgroundColor = UIColor.green
        } else {
            doubleTapView.backgroundColor = UIColor.yellow
        }
    }

    // Long press action
    func handleLongPress(gesture: UILongPressGestureRecognizer) {
        label.text = "Long press recognized"

        // example task: show an alert
        if gesture.state == UIGestureRecognizerState.began {
            let alert = UIAlertController(title: "Long Press", message: "Can I help you?", preferredStyle: UIAlertControllerStyle.alert)
            alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil))
            self.present(alert, animated: true, completion: nil)
        }
    }

    // Pan action
    func handlePan(gesture: UIPanGestureRecognizer) {
        label.text = "Pan recognized"

        // example task: drag view
        let location = gesture.location(in: view) // root view
        panView.center = location
    }

    // Swipe action
    func handleSwipe(gesture: UISwipeGestureRecognizer) {
        label.text = "Swipe recognized"

        // example task: animate view off screen
        let originalLocation = swipeView.center
        if gesture.direction == UISwipeGestureRecognizerDirection.right {
            UIView.animate(withDuration: 0.5, animations: {
                self.swipeView.center.x += self.view.bounds.width
                }, completion: { (value: Bool) in
                    self.swipeView.center = originalLocation
            })
        } else if gesture.direction == UISwipeGestureRecognizerDirection.left {
            UIView.animate(withDuration: 0.5, animations: {
                self.swipeView.center.x -= self.view.bounds.width
                }, completion: { (value: Bool) in
                    self.swipeView.center = originalLocation
            })
        }
    }

    // Pinch action
    func handlePinch(gesture: UIPinchGestureRecognizer) {
        label.text = "Pinch recognized"

        if gesture.state == UIGestureRecognizerState.changed {
            let transform = CGAffineTransform(scaleX: gesture.scale, y: gesture.scale)
            pinchView.transform = transform
        }
    }

    // Rotate action
    func handleRotate(gesture: UIRotationGestureRecognizer) {
        label.text = "Rotate recognized"

        if gesture.state == UIGestureRecognizerState.changed {
            let transform = CGAffineTransform(rotationAngle: gesture.rotation)
            rotateView.transform = transform
        }
    }
}
  • You can add multiple gesture recognizers to a single view. For the sake of simplicity, though, I didn't do that (except for the swipe gesture). If you need to for your project, you should read the gesture recognizer documentation. It is fairly understandable and helpful.
  • Known issues with my examples above: (1) Pan view resets its frame on next gesture event. (2) Swipe view comes from the wrong direction on the first swipe. (These bugs in my examples should not affect your understanding of how Gestures Recognizers work, though.)

@Er.Vihar: That is a good point. I'll add this answer to my list of things to update. Until then, other users can take note of your comment.

ios - How to add a touch event to a UIView? - Stack Overflow

ios objective-c events uiview touch
Rectangle 27 68

Adding a Gesture in the Interface Builder

There are a number of commonly used touch events (or gestures) that you can be notified of when you add a Gesture Recognizer to your view. They following gesture types are supported by default:

UITapGestureRecognizer
UILongPressGestureRecognizer
  • UIPanGestureRecognizer Pan (moving your finger across the screen)
UISwipeGestureRecognizer
  • UIPinchGestureRecognizer Pinch (moving two fingers together or apart - usually to zoom)
UIRotationGestureRecognizer

In addition to these, you can also make your own custom gesture recognizer.

Drag a gesture recognizer from the object library onto your view.

Control drag from the gesture in the Document Outline to your View Controller code in order to make an Outlet and an Action.

To add a gesture programmatically, you (1) create a gesture recognizer, (2) add it to a view, and (3) make a method that is called when the gesture is recognized.

import UIKit
class ViewController: UIViewController {

    @IBOutlet weak var myView: UIView!

    override func viewDidLoad() {
        super.viewDidLoad()

        // 1. create a gesture recognizer (tap gesture)
        let tapGesture = UITapGestureRecognizer(target: self, action: #selector(handleTap(sender:)))

        // 2. add the gesture recognizer to a view
        myView.addGestureRecognizer(tapGesture)
    }

    // 3. this method is called when a tap is recognized
    func handleTap(sender: UITapGestureRecognizer) {
        print("tap")
    }
}
  • The sender parameter is optional. If you don't need a reference to the gesture then you can leave it out. If you do so, though, remove the (_:) after the action method name when creating the gesture.
handleTap
action: #selector(someMethodName(sender:))

You can study the gesture recognizers that I added to these views to see how they work.

Here is the code for that project:

import UIKit
class ViewController: UIViewController {

    @IBOutlet weak var tapView: UIView!
    @IBOutlet weak var doubleTapView: UIView!
    @IBOutlet weak var longPressView: UIView!
    @IBOutlet weak var panView: UIView!
    @IBOutlet weak var swipeView: UIView!
    @IBOutlet weak var pinchView: UIView!
    @IBOutlet weak var rotateView: UIView!
    @IBOutlet weak var label: UILabel!

    override func viewDidLoad() {
        super.viewDidLoad()

        // Tap
        let tapGesture = UITapGestureRecognizer(target: self, action: #selector(handleTap))
        tapView.addGestureRecognizer(tapGesture)

        // Double Tap
        let doubleTapGesture = UITapGestureRecognizer(target: self, action: #selector(handleDoubleTap))
        doubleTapGesture.numberOfTapsRequired = 2
        doubleTapView.addGestureRecognizer(doubleTapGesture)

        // Long Press
        let longPressGesture = UILongPressGestureRecognizer(target: self, action: #selector(handleLongPress(gesture:)))
        longPressView.addGestureRecognizer(longPressGesture)

        // Pan
        let panGesture = UIPanGestureRecognizer(target: self, action: #selector(handlePan(gesture:)))
        panView.addGestureRecognizer(panGesture)

        // Swipe (right and left)
        let swipeRightGesture = UISwipeGestureRecognizer(target: self, action: #selector(handleSwipe(gesture:)))
        let swipeLeftGesture = UISwipeGestureRecognizer(target: self, action: #selector(handleSwipe(gesture:)))
        swipeRightGesture.direction = UISwipeGestureRecognizerDirection.right
        swipeLeftGesture.direction = UISwipeGestureRecognizerDirection.left
        swipeView.addGestureRecognizer(swipeRightGesture)
        swipeView.addGestureRecognizer(swipeLeftGesture)

        // Pinch
        let pinchGesture = UIPinchGestureRecognizer(target: self, action: #selector(handlePinch(gesture:)))
        pinchView.addGestureRecognizer(pinchGesture)

        // Rotate
        let rotateGesture = UIRotationGestureRecognizer(target: self, action: #selector(handleRotate(gesture:)))
        rotateView.addGestureRecognizer(rotateGesture)

    }

    // Tap action
    func handleTap() {
        label.text = "Tap recognized"

        // example task: change background color
        if tapView.backgroundColor == UIColor.blue {
            tapView.backgroundColor = UIColor.red
        } else {
            tapView.backgroundColor = UIColor.blue
        }

    }

    // Double tap action
    func handleDoubleTap() {
        label.text = "Double tap recognized"

        // example task: change background color
        if doubleTapView.backgroundColor == UIColor.yellow {
            doubleTapView.backgroundColor = UIColor.green
        } else {
            doubleTapView.backgroundColor = UIColor.yellow
        }
    }

    // Long press action
    func handleLongPress(gesture: UILongPressGestureRecognizer) {
        label.text = "Long press recognized"

        // example task: show an alert
        if gesture.state == UIGestureRecognizerState.began {
            let alert = UIAlertController(title: "Long Press", message: "Can I help you?", preferredStyle: UIAlertControllerStyle.alert)
            alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil))
            self.present(alert, animated: true, completion: nil)
        }
    }

    // Pan action
    func handlePan(gesture: UIPanGestureRecognizer) {
        label.text = "Pan recognized"

        // example task: drag view
        let location = gesture.location(in: view) // root view
        panView.center = location
    }

    // Swipe action
    func handleSwipe(gesture: UISwipeGestureRecognizer) {
        label.text = "Swipe recognized"

        // example task: animate view off screen
        let originalLocation = swipeView.center
        if gesture.direction == UISwipeGestureRecognizerDirection.right {
            UIView.animate(withDuration: 0.5, animations: {
                self.swipeView.center.x += self.view.bounds.width
                }, completion: { (value: Bool) in
                    self.swipeView.center = originalLocation
            })
        } else if gesture.direction == UISwipeGestureRecognizerDirection.left {
            UIView.animate(withDuration: 0.5, animations: {
                self.swipeView.center.x -= self.view.bounds.width
                }, completion: { (value: Bool) in
                    self.swipeView.center = originalLocation
            })
        }
    }

    // Pinch action
    func handlePinch(gesture: UIPinchGestureRecognizer) {
        label.text = "Pinch recognized"

        if gesture.state == UIGestureRecognizerState.changed {
            let transform = CGAffineTransform(scaleX: gesture.scale, y: gesture.scale)
            pinchView.transform = transform
        }
    }

    // Rotate action
    func handleRotate(gesture: UIRotationGestureRecognizer) {
        label.text = "Rotate recognized"

        if gesture.state == UIGestureRecognizerState.changed {
            let transform = CGAffineTransform(rotationAngle: gesture.rotation)
            rotateView.transform = transform
        }
    }
}
  • You can add multiple gesture recognizers to a single view. For the sake of simplicity, though, I didn't do that (except for the swipe gesture). If you need to for your project, you should read the gesture recognizer documentation. It is fairly understandable and helpful.
  • Known issues with my examples above: (1) Pan view resets its frame on next gesture event. (2) Swipe view comes from the wrong direction on the first swipe. (These bugs in my examples should not affect your understanding of how Gestures Recognizers work, though.)

@Er.Vihar: That is a good point. I'll add this answer to my list of things to update. Until then, other users can take note of your comment.

ios - How to add a touch event to a UIView? - Stack Overflow

ios objective-c events uiview touch
Rectangle 27 50

UIControl *headerView = ...
[headerView addTarget:self action:@selector(myEvent:) forControlEvents:UIControlEventTouchDown];

i mean headerView extends from UIControl.

UITapGestureRecognizer
Tap
UIControlEventTouchDown
UIControlEventTouchUpInside
UIView
UIControl
addTarget:action:forControlEvents:

Also note that a UIControl inherits from UIView. For my purposes all I had to do was a simple switch of subclass type.

you can set its class to UIControl @RobertJoseph .. Go to xib file and set the View Custom class to UIControl . now you can handle event in it..

So why this a better solution again since I'm changing inheritance just to handle taps?

ios - How to add a touch event to a UIView? - Stack Overflow

ios objective-c events uiview touch
Rectangle 27 50

UIControl *headerView = ...
[headerView addTarget:self action:@selector(myEvent:) forControlEvents:UIControlEventTouchDown];

i mean headerView extends from UIControl.

UITapGestureRecognizer
Tap
UIControlEventTouchDown
UIControlEventTouchUpInside
UIView
UIControl
addTarget:action:forControlEvents:

Also note that a UIControl inherits from UIView. For my purposes all I had to do was a simple switch of subclass type.

you can set its class to UIControl @RobertJoseph .. Go to xib file and set the View Custom class to UIControl . now you can handle event in it..

So why this a better solution again since I'm changing inheritance just to handle taps?

ios - How to add a touch event to a UIView? - Stack Overflow

ios objective-c events uiview touch
Rectangle 27 15

Based on the accepted answer you can define a macro:

#define handle_tap(view, delegate, selector) do {\
    view.userInteractionEnabled = YES;\
    [view addGestureRecognizer: [[UITapGestureRecognizer alloc] initWithTarget:delegate action:selector]];\
} while(0)
release
handle_tap(userpic, self, @selector(onTapUserpic:));

If you create the view in storyboard, don't forget to enable the "user interaction enabled" option.

where we should define macros in .h or .m and what should be the name of the parameters . i mean #define handle_tap(UIView view,Delegate delegate , SEL selector)do..

sooo convenient is sooo many ways, thank you!! A+++

ios - How to add a touch event to a UIView? - Stack Overflow

ios objective-c events uiview touch
Rectangle 27 15

Based on the accepted answer you can define a macro:

#define handle_tap(view, delegate, selector) do {\
    view.userInteractionEnabled = YES;\
    [view addGestureRecognizer: [[UITapGestureRecognizer alloc] initWithTarget:delegate action:selector]];\
} while(0)
release
handle_tap(userpic, self, @selector(onTapUserpic:));

If you create the view in storyboard, don't forget to enable the "user interaction enabled" option.

where we should define macros in .h or .m and what should be the name of the parameters . i mean #define handle_tap(UIView view,Delegate delegate , SEL selector)do..

sooo convenient is sooo many ways, thank you!! A+++

ios - How to add a touch event to a UIView? - Stack Overflow

ios objective-c events uiview touch
Rectangle 27 9

You can achieve this by adding Gesture Recogniser in your code.

// Declare the Gesture.
UITapGestureRecognizer *gesRecognizer = [[UITapGestureRecognizer alloc] 
                                          initWithTarget:self 
                                          action:@selector(handleTap:)];
gesRecognizer.delegate = self;

// Add Gesture to your view.
[yourView addGestureRecognizer:gesRecognizer];
// Declare the Gesture Recogniser handler method.
- (void)handleTap:(UITapGestureRecognizer *)gestureRecognizer{
   NSLog(@"Tapped");
}
@property (strong, nonatomic) IBOutlet UIView *localView;

EDIT: *localView is the white box in Main.storyboard from below

i am having multiple view so can i can the sender id ??

You have to go to the inner subview, then you can paas the sender.---------for (UIView *view in self.topicScrollView.subviews) {//Go Inside the superview if ([view isKindOfClass:[UIButton class]]) { // Go to that particular view // Here you have reached upto that point. } }

ios - How to add a touch event to a UIView? - Stack Overflow

ios objective-c events uiview touch
Rectangle 27 9

You can achieve this by adding Gesture Recogniser in your code.

// Declare the Gesture.
UITapGestureRecognizer *gesRecognizer = [[UITapGestureRecognizer alloc] 
                                          initWithTarget:self 
                                          action:@selector(handleTap:)];
gesRecognizer.delegate = self;

// Add Gesture to your view.
[yourView addGestureRecognizer:gesRecognizer];
// Declare the Gesture Recogniser handler method.
- (void)handleTap:(UITapGestureRecognizer *)gestureRecognizer{
   NSLog(@"Tapped");
}
@property (strong, nonatomic) IBOutlet UIView *localView;

EDIT: *localView is the white box in Main.storyboard from below

i am having multiple view so can i can the sender id ??

You have to go to the inner subview, then you can paas the sender.---------for (UIView *view in self.topicScrollView.subviews) {//Go Inside the superview if ([view isKindOfClass:[UIButton class]]) { // Go to that particular view // Here you have reached upto that point. } }

ios - How to add a touch event to a UIView? - Stack Overflow

ios objective-c events uiview touch
Rectangle 27 5

Heres a Swift version:

// MARK: Gesture Extensions
extension UIView {

    func addTapGesture(#tapNumber: Int, target: AnyObject, action: Selector) {
        let tap = UITapGestureRecognizer (target: target, action: action)
        tap.numberOfTapsRequired = tapNumber
        addGestureRecognizer(tap)
        userInteractionEnabled = true
    }

    func addTapGesture(#tapNumber: Int, action: ((UITapGestureRecognizer)->())?) {
        let tap = BlockTap (tapCount: tapNumber, fingerCount: 1, action: action)
        addGestureRecognizer(tap)
        userInteractionEnabled = true
    }
}
BlockTap

ios - How to add a touch event to a UIView? - Stack Overflow

ios objective-c events uiview touch
Rectangle 27 5

Heres a Swift version:

// MARK: Gesture Extensions
extension UIView {

    func addTapGesture(#tapNumber: Int, target: AnyObject, action: Selector) {
        let tap = UITapGestureRecognizer (target: target, action: action)
        tap.numberOfTapsRequired = tapNumber
        addGestureRecognizer(tap)
        userInteractionEnabled = true
    }

    func addTapGesture(#tapNumber: Int, action: ((UITapGestureRecognizer)->())?) {
        let tap = BlockTap (tapCount: tapNumber, fingerCount: 1, action: action)
        addGestureRecognizer(tap)
        userInteractionEnabled = true
    }
}
BlockTap

ios - How to add a touch event to a UIView? - Stack Overflow

ios objective-c events uiview touch
Rectangle 27 4

import UIKit

extension UIView {

func addTapGesture(tapNumber : Int, target: Any , action : Selector) {

    let tap = UITapGestureRecognizer(target: target, action: action)
    tap.numberOfTapsRequired = tapNumber
    addGestureRecognizer(tap)
    isUserInteractionEnabled = true

  }
}
yourView.addTapGesture(tapNumber: 1, target: self, action: #selector(yourMethod))

ios - How to add a touch event to a UIView? - Stack Overflow

ios objective-c events uiview touch
Rectangle 27 4

import UIKit

extension UIView {

func addTapGesture(tapNumber : Int, target: Any , action : Selector) {

    let tap = UITapGestureRecognizer(target: target, action: action)
    tap.numberOfTapsRequired = tapNumber
    addGestureRecognizer(tap)
    isUserInteractionEnabled = true

  }
}
yourView.addTapGesture(tapNumber: 1, target: self, action: #selector(yourMethod))

ios - How to add a touch event to a UIView? - Stack Overflow

ios objective-c events uiview touch
Rectangle 27 12

If you want to return YES if the touch is inside the view where you implement this method, use this code: (in case you want to add gesture recognizers to a subview that is located outside the container's bounds)

- (BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event
{
    if ([super pointInside:point withEvent:event])
    {
        return YES;
    }
    else
    {
        return CGRectContainsPoint(subview.frame, point);
    }
}

events - iphone - determine if touch occurred in subview of a uiview -...

iphone events uiview touch subview
Rectangle 27 2

let tapGestureRecognizer: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(handleTapGestureRecognizer(_:)))
view.addGestureRecognizer(tapGestureRecognizer)

func handleTapGestureRecognizer(_ gestureRecognizer: UITapGestureRecognizer) {

}

ios - How to add a touch event to a UIView? - Stack Overflow

ios objective-c events uiview touch
Rectangle 27 297

[aView convertPoint:localPosition toView:nil];

... converts a point in local coordinate space to window coordinates. You can use this method to calculate a view's origin in window space like this:

[aView.superview convertPoint:aView.frame.origin toView:nil];

2014 Edit: Looking at the popularity of Matt__C's comment it seems reasonable to point out that the coordinates...

  • don't change when rotating the device.
  • always have their origin in the top left corner of the unrotated screen.
  • are window coordinates: The coordinate system ist defined by the bounds of the window. The screen's and device coordinate systems are different and should not be mixed up with window coordinates.

Be aware that specifying nil in the toView parameter gives you device co-ordinates, which won't be what you want if you are not in portrait orientation. See convertpointtoview-in-landscape-mode-giving-wrong-values

This method kept returning aView.frame.origin for me. It took me a whlie to realize my view's superview did not have a superview itself.

If your superView did not have a superView your view should not be seen at all

[view.superview convertPoint:view.frame.origin toView:[UIApplication sharedApplication].keyWindow.rootViewController.view]

Sign up for our newsletter and get our top new questions delivered to your inbox (see an example).

cocoa touch - iPhone - Get Position of UIView within entire UIWindow -...

iphone cocoa-touch ios uiview uiwindow