Dragging a View Around the Screen

Recall that virtually every “thing” you see on an iOS device screen is descended from the UIView class. If you want your user to be able to drag something around the screen, you’ll define the element as a UIView subclass. In HTML, CSS, DOM, and JavaScript terms, every view is the equivalent of an absolute-positioned element. It has a location within the coordinate system of the parent view and exists as its own layer that you can move independently of other views (and it takes its nested subviews along for the ride). In JavaScript on a browser running on a traditional computer, you use mouse events to detect when a user has engaged the element for movement, when the mouse moves the element, and when the user releases the mouse button. The equivalent events in iOS are called touch events.

Because UIView inherits from UIResponder, all views—when explicitly enabled—are capable of reacting to touch events. Touch events send messages to the view under the spot interpreted by the system as being the intended event coordinate. Despite the pudginess of fingers compared to the extremely small pixel points on the screen, the system calculates a point to report for each event. The ability to interpret and calculate this disparity well is a hallmark of a good touchscreen experience. We developers receive the benefits of that engineering for free.

A touch can be a quick tap or a lengthy drag around the screen. To accommodate those possibilities, the system sends ...

Get Learning the iOS 4 SDK for JavaScript Programmers now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.