Swift views and controls

 A view displays content, whereas a control is used to modify it in some way. A control (UIControl) is a subclass of UIView. views can not have action. But Gesture recognizers can be used to add actions for the views.

An image view isn’t a control, so it’s not designed to respond to input in the same way that a control—such as a button—responds. For example, you can’t simply create an action method that’s triggered when a user taps on an image view. (If you try to Control-drag from the image view to your code, you’ll notice that you can’t select Action in the Connection field.)

Fortunately, it’s quite easy to give a view the same capabilities as a control by adding a gesture recognizer to it. Gesture recognizers are objects that you attach to a view that allow the view to respond to actions the way a control does. Gesture recognizers interpret touches to determine whether they correspond to a specific gesture, such as a swipe, pinch, or rotation. You can write an action method that occurs when a gesture recognizer recognizes its assigned gesture, which is exactly what you need to do for the image view.

Attach a tap gesture recognizer (UITapGestureRecognizer) to the image view, which will recognize when a user has tapped the image view. You can do this easily in your storyboard.

To add a tap gesture recognizer to your image view

  1. Open the Object library. (To open it quickly, choose View > Utilities > Show Object Library.)

  2. In the Object library, type tap gesture in the filter field to find the Tap Gesture Recognizer object quickly.

  3. Drag a Tap Gesture Recognizer object from the Object library to your scene, and place it on top of the image view

posted @ 2015-06-29 22:17  uu2008  阅读(123)  评论(0编辑  收藏  举报