Showing posts with label touch. Show all posts
Showing posts with label touch. Show all posts

Friday, December 9, 2016

Part 5 - UIView's Multiple Touch Property

  • By default a UIView can only receive one touch.
  • Enabling Multiple Touch allows the UIView to receive more than one touch.
  • In code you reference the multipleTouchEnabled property

Example

In this example the tan area has Multiple Touch on while the white area does not.


Code

 
class ViewController: UIViewController {

    @IBOutlet weak var touchesLabel: UILabel!
    @IBOutlet weak var touchPointsLabel: UILabel!
    
    override func touchesBegan(_ touches: Set, with event: UIEvent?) {
        // Number of Touches
        touchesLabel.text = "\(touches.count)"
        
        // Coordinates of the Touches
        var coordinates = ""
        var touchNumber = 0
        
        for touch in touches {
            touchNumber = touchNumber + 1
            let point = touch.location(in: view)
            coordinates = coordinates + "Touch \(touchNumber): [\(point.x), \(point.y)] \n"
        }
        
        touchPointsLabel.text = coordinates
    }
}
 



(Xcode 8, Swift 3.0)

Saturday, May 7, 2016

Touch and Drag Objects

If you want to touch and drag an object around the screen you can do this by setting the object's center property to the location of your touch.
In this example I have an image (UIImageView) that I want to touch and drag.

Create New Class

import UIKit

class DraggableImage: UIImageView {
    
    override func touchesMoved(touches: Set, withEvent event: UIEvent?) {
        if let touch = touches.first {
            let position = touch.locationInView(superview)
            center = CGPointMake(position.x, position.y)
        }
    }
}
I override touchesMoved and am getting the position of my touch and making the center of my image the same position as my touch.


Setup Image in Xcode

In this example I am using a UIImageView. I dropped an image on my storyboard and I have to make 2 changes.
  1. Set the Custom Class
    Set the class to the class that overrides touchesMoved:
  2. Set Interaction
    Make sure "User Interaction Enabled" is checked. This allows your touchesMoved override to receive touch event messages.
    I also unchecked "Multiple Touch" because I'm only using one finger to move my object.
That is it! You should be able to run and move your image. (Written for Xcode 7.3, Swift 2.2)

SwiftUI Search & Filter with Combine - Part 3 (iOS, Xcode 13, SwiftUI, 2...

In part 3 of the Searchable video series, I show you how to use Combine in #SwiftUI for the search and filter logic connected to the searcha...