Rectangle 27 2

You'll have to setup some sort of collision detection. When you get a touch event in the frame, then call your "hit test" method. That method will simply check whether or not the touch point in the frame intersects with the curve.

Thanks! I implemented the collision detection using CGPathContainsPoint.

iphone - How to catch touch events for CG content in UIView? - Stack O...

iphone objective-c uiview core-graphics
Rectangle 27 113

A UIImageView is derived from a UIView which is derived from UIResponder so it's ready to handle touch events. You'll want to provide the touchesBegan, touchesMoved, and touchesEnded methods and they'll get called if the user taps the image. If all you want is a tap event, it's easier to just use a custom button with the image set as the button image. But if you want finer-grain control over taps, moves, etc. this is the way to go.

I tried that but never the less I don't receive the touchesBegan events... why is that?

userInteractionEnabled

iphone - how can i detect the touch event of an UIImageView - Stack Ov...

iphone uiimageview uitouch
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 5

You should to put your code in "touchesMoved:withEvent:" method of your UIView. If your View will handle this event by yourself, then it should not bubble to superview

while I do overwrote touchesMoved:withEvent: but the scrollView still scrolls when I drag on its subview who have overwritten touchesMoved:withEvent:

in fact, it is such a architecture, I use a total view as the subview of scrollview, and then put all the picture views on total view.I do this since I need to scale all picture views at the same time. The total View didn't overwrote touchesMoved:withEvent: (only picture view did),is the where the problem lies?

You can try to set canCancelContentTouches to NO in your UIScrollView. And set exclusiveTouch to YES in your UIView with image

iphone - how to prevent a touch event passed to a UIView's superview? ...

iphone cocoa-touch uiscrollview
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 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 4

Try setting userInteractionEnabled to NO on your dimmer view. This should tell the view not to interact with touch events, which should allow them to continue down to the views beneath the dimmer.

iphone - IOS: setting 'dimmer' view's alpha to greater than 0.0 disabl...

iphone uiview alpha touch-events
Rectangle 27 135

Instead add a button with Custom style (no button graphics unless you specify images) over the UIImageView. Then attach whatever methods you want called to that.

You can use that technique for many cases where you really want some area of the screen to act as a button instead of messing with the Touch stuff.

I have added a button at the navigation bar and I can also handle touch events. However, I want to add an round image on this button. Could you let me know how can I do that programmatically? Also, could you let me know how can I set the button property to "custom" programmatically?

Look at the docs for UIButton - you need to set background images for a control state, you'll want different images for Normal vs. Selected/Highlighted. The button style is what you set to UIButtonStyleCustom, I believe - again, look at the docs for the style property on UIButton.

Isn't adding a UIButton on top of the UIImageView a little over the top? You're adding an extra object, whereas you could just implement the touches methods of the already existing UIImageView object. No?

If you look at the size of a UIButton in memory, it's virtually nothing and you only have a few per screen. What you get for free is the whole target action wiring for different states (like touch up inside) and also nice behavior like not triggering when you press down but slide a finger to the side. Basically buttons are one of the most finely crafted objects in the whole system and to think you are going to do custom touch code that works better is madness. Use that which is cheap and works well, save the custom work for things that the frameworks don't already handle for you.

You can also overlay a UIControl if all you need are touch events (via addTaget:action:forControlEvents:). It's a bit cheaper than a UIButton which has images and several states. Also, I use preprocessor conditionals to change the overlayed control's background color to pink so I can see exactly where they are (and remember that they exist :-).

iphone - how can i detect the touch event of an UIImageView - Stack Ov...

iphone uiimageview uitouch