How to add a touch event to a UIView?
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.
UIView touch event in controller
You will have to add it through code. First, create the view and add it to the hierarchy:
var myView = UIView(frame: CGRectMake(100, 100, 100, 100))
self.view.addSubview(myView)
After that initialize gesture recognizer. Until Swift 2:
let gesture = UITapGestureRecognizer(target: self, action: "someAction:")
After Swift 2:
let gesture = UITapGestureRecognizer(target: self, action: #selector (self.someAction (_:)))
Then bind it to the view:
self.myView.addGestureRecognizer(gesture)
Swift 3:
func someAction(_ sender:UITapGestureRecognizer){
// do other task
}
Swift 4 just add @objc
before func
:
@objc func someAction(_ sender:UITapGestureRecognizer){
// do other task
}
Swift UI:
Text("Tap me!").tapAction {
print("Tapped!")
}
How to send touch event to a UIView on iOS
UIButton *btnInPicker = nil;
for( UIView *_subView in self.broadcastPicker.subviews) {
if( [_subView isKindOfClass:[UIButton class]] ) {
btnInPicker = (UIButton *)_subView;
break;
}
}
if(btnInPicker) {
[btnInPicker sendActionsForControlEvents:UIControlEventTouchDown];
}
but it has a issue:
Unbalanced calls to begin/end appearance transitions for
Touch Event on UIView
A very general way to get touches is to override these methods in a custom UIView subclass:
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event;
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event;
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event;
- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event
The official docs for these methods is under Responding to Touch Events in the UIResponder class docs (UIView inherits those methods since it's a subclass of UIResponder). Longer and more introductory docs can be found in the Event Handling Guide for iOS.
If you just want to detect a tap (touch-down, then touch-up within your view), it's easiest to add a UIButton
as a subview of your view, and add your own custom method as a target/action pair for that button. Custom buttons are invisible by default, so it wouldn't affect the look of your view.
If you're looking for more advanced interactions, it's also good to know about the UIGestureRecognizer
class.
How to add touch event for custom UIControl and determine the touched item in swift 5
First of all, all interactions with UILabel are disabled by default. To change it, set isUserInteractionEnabled to true.
import UIKit
@IBDesignable
class SomeUI: UIControl {
private var componentsAdded = false
let labelOne = UILabel()
private let labelTwo = UILabel()
required init?(coder: NSCoder) {
super.init(coder: coder)
labelOne.isUserInteractionEnabled = true
}
override func draw(_ rect: CGRect) {
if !componentsAdded {
componentsAdded = true
self.addSubview(labelOne)
labelOne.text = "one"
labelOne.sizeToFit()
self.addSubview(labelTwo)
labelTwo.text = "two"
labelTwo.sizeToFit()
}
labelOne.center = CGPoint(x: 10, y: 10)
labelTwo.center = CGPoint(x: 10, y: 40)
}
}
\\ File: ViewController.swift
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
@IBOutlet weak var someLabel: UILabel!
@IBOutlet weak var sui: SomeUI!
@IBAction func changeLabel(_ gestureRecognizer: UITapGestureRecognizer) {
let view = gestureRecognizer.view
let loc = gestureRecognizer.location(in: view)
let subview = sui.hitTest(loc, with: nil)
switch subview {
case sui.labelOne: print("1") someLabel.text = "label one tapped"
case sui.labelTwo: print("2") someLabel.text = "label two tapped"
default: print("0") someLabel.text = "TAPPIO?" }
}
}
In Storyboard add a Tap Gesture Recognizer and set its "Sent Actions" to "changeLabel", "Referencing outlet collections" to your custom SomeUI IBOutlet referenced here by "sui" property
@IBOutlet weak var sui: SomeUI!
Touch Event on UIView
A very general way to get touches is to override these methods in a custom UIView subclass:
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event;
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event;
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event;
- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event
The official docs for these methods is under Responding to Touch Events in the UIResponder class docs (UIView inherits those methods since it's a subclass of UIResponder). Longer and more introductory docs can be found in the Event Handling Guide for iOS.
If you just want to detect a tap (touch-down, then touch-up within your view), it's easiest to add a UIButton
as a subview of your view, and add your own custom method as a target/action pair for that button. Custom buttons are invisible by default, so it wouldn't affect the look of your view.
If you're looking for more advanced interactions, it's also good to know about the UIGestureRecognizer
class.
Related Topics
How to Detect the End of Loading of Uitableview
Get a List of All Contacts on Ios
Making Text Bold Using Attributed String in Swift
Getting iOS System Uptime, That Doesn't Pause When Asleep
How to Pass Data Using Notificationcenter in Swift 3.0 and Nsnotificationcenter in Swift 2.0
Drawing a Route in Mapkit in Ios
Swiftui | Using Ondrag and Ondrop to Reorder Items Within One Single Lazygrid
How to Compare Two Uiimage Objects
How to Crop a Uiimageview to a New Uiimage in 'Aspect Fill' Mode
Swift - Stored Values Order Is Completely Changed in Dictionary
Didregisterforremotenotificationswithdevicetoken Not Called in Ios8, But Didregister...Settings Is
How to Use Auto Layout to Move Other Views When a View Is Hidden
Send Post Request Using Nsurlsession
Move a View Up Only When the Keyboard Covers an Input Field
Check For Internet Connection Availability in Swift
Error When Testing on iOS Simulator: Couldn't Register With the Bootstrap Server