Learn how to create a simple app that handles multitouch input.
Consider the app shown in Figure 1, where a single main view that draws a gray circle at each touch location. When a touch ends, the circle disappears. When the user’s fingers move, the underlying circles move with them.
The creation of this app begins with the Single View app template in Xcode. This type of app has a single view controller whose view—in this case a custom subclass of UIView called TouchableView—fills the screen. The view contains only a label initially, but the app programmatically adds subviews later. Figure 2 shows the storyboard for the view controller.
Implement the TouchableView Class
The TouchableView class overrides the inherited touchesBegan(_:with:), touchesMoved(_:with:), touchesEnded(_:with:), and touchesCancelled(_:with:) methods. These methods handle the creation and management of subviews that draw the gray circles at each touch location. Specifically, these methods do the following:
Listing 1 shows the main implementation of the TouchableView class and its touch handling methods. Each method iterates through the touches and performs the needed actions. The touchViews dictionary uses the UITouch objects as keys to retrieve the subviews the user is manipulating onscreen.
Several helper methods handle creation, management, and disposal of the subviews, as shown in Listing 2. The createViewForTouch method creates a new TouchSpotView object and adds it to the TouchableView object, animating the view to its full size. The removeViewForTouch method removes the corresponding subview and updates the class data structures. The viewForTouch method is a convenience method for retrieving the view associated with a given touch event.
Implement the TouchSpotView Class
The TouchSpotView class (shown in Listing 3) represents the custom subviews that draw the gray circles onscreen. TouchSpotView maintains its circular shape by setting the cornerRadius property of the layer each time its bounds property changes.