Tap gesture event not gettint called. I may be doing something wrong, but please have a look (I tried adding recognizer to self.view but still no luck) :
LoginViewController
class LoginViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let container = UIView()
container.heightAnchor.constraintEqualToConstant(50).active = true
let myVC1 = MyViewController()
let myVC2 = MyViewController()
let myVC3 = MyViewController()
let myVC4 = MyViewController()
let myStackView = UIStackView(arrangedSubviews: [myVC1.view, myVC2.view, myVC3.view, myVC4.view])
myStackView.spacing = 10
myStackView.alignment = .Fill
myStackView.distribution = .EqualSpacing
container.addSubview(myStackView)
view.addSubview(container)
}
}
MyViewController
class MyViewController: UIViewController, UIGestureRecognizerDelegate {
let ImageView = UIImageView()
override func viewDidLoad() {
super.viewDidLoad()
ImageView.backgroundColor = UIColor.blueColor()
let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(pressedSocialMediaItem(_:)))
tapGestureRecognizer.delegate = self
tapGestureRecognizer.numberOfTapsRequired = 1
ImageView.userInteractionEnabled = true
ImageView.addGestureRecognizer(tapGestureRecognizer)
view.addSubview(ImageView)
}
func pressedSocialMediaItem(sender : UITapGestureRecognizer) {
print("PRESSED ! ")
}
}
I suggest using MyViewController.pressedSocialMediaItem, so your code should work like this.
class MyViewController: UIViewController, UIGestureRecognizerDelegate {
let ImageView = UIImageView()
override func viewDidLoad() {
super.viewDidLoad()
ImageView.backgroundColor = UIColor.blueColor()
let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(MyViewController.pressedSocialMediaItem(_:)))
tapGestureRecognizer.delegate = self
tapGestureRecognizer.numberOfTapsRequired = 1
ImageView.userInteractionEnabled = true
ImageView.addGestureRecognizer(tapGestureRecognizer)
view.addSubview(ImageView)
}
func pressedSocialMediaItem(sender : UITapGestureRecognizer) {
print("PRESSED ! ")
}
}
I have tested the following on my machine and it works:
import UIKit
class ViewController: UIViewController, UIGestureRecognizerDelegate {
#IBOutlet weak var imageView: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
imageView.backgroundColor = UIColor.blueColor()
let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(ViewController.pressedSocialMediaItem(_:)))
tapGestureRecognizer.delegate = self
tapGestureRecognizer.numberOfTapsRequired = 1
imageView.userInteractionEnabled = true
imageView.addGestureRecognizer(tapGestureRecognizer)
view.addSubview(imageView)
}
func pressedSocialMediaItem(sender : UITapGestureRecognizer) {
print("PRESSED ! ")
}
}
Okey, so I got it working somehow. All I need to do was to add view controllers inside my LoginViewController like so:
self.addChildViewController(myVC1)
Instead of using view.addSubview(container)
Notice: I'm not sure it is the correct way of doing this, and please comment if it's not. Meanwhile it solves my problem.
Related
I have implemented the new SearchController with its searchBar and the searchResultsController.
Here is how I implemented it :
The resultViewController:
lazy var resultViewController: SearchResultViewController = {
let storyboard = UIStoryboard.init(name: "Main", bundle: nil)
let searchResultViewController = storyboard.instantiateViewController(withIdentifier: "SearchResultViewController") as! SearchResultViewController
searchResultViewController.delegate = self
return searchResultViewController
}()
And this is the SearchController:
lazy var searchController: UISearchController = {
let searchController = UISearchController(searchResultsController: resultViewController)
searchController.searchBar.delegate = self
searchController.obscuresBackgroundDuringPresentation = true
searchController.searchResultsUpdater = self
searchController.searchBar.placeholder = "Search.city.label".localizable()
searchController.searchBar.tintColor = UIColor.white
searchController.searchBar.barTintColor = UIColor.white
UITextField.appearance(whenContainedInInstancesOf: [type(of: searchController.searchBar)]).tintColor = UIColor(red:0.00, green:0.47, blue:0.78, alpha:1.0)
if let textfield = searchController.searchBar.value(forKey: "searchField") as? UITextField {
if let backgroundview = textfield.subviews.first {
// Background color
backgroundview.backgroundColor = UIColor.white
// Rounded corner
backgroundview.layer.cornerRadius = 10;
backgroundview.clipsToBounds = true;
}
}
definesPresentationContext = true
return searchController
}()
In my viewWillAppear I set the navigationItem.searchController :
self.searchController.isActive = true
if #available(iOS 11.0, *) {
self.navigationItem.searchController = searchController
self.navigationItem.hidesSearchBarWhenScrolling = true
} else {
// Fallback on earlier versions
}
I have been able to handle the cancelButtonClicked :
extension HomeViewController: UISearchBarDelegate {
func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
searchBar.endEditing(true)
self.searchController.isActive = false
}
}
This is doing the "cancel" animation, hiding keyboard + inactive state on searchBar/searchController. Both at the same time, with 1 tap on cancel Button.
But I am unable to achieve this when the user tap anywhere on the view.
I tried with tap gesture but it requires me 2 tap to achieve the same behavior.
NB:
I got an UICollectionView in my UIViewController, which takes all the place in the UIView.
Here is what I have tried :
override func viewDidLoad() {
super.viewDidLoad()
handleTapAnywhereToRemoveKeyboard()
}
func handleTapAnywhereToRemoveKeyboard() {
let singleTapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(self.singleTap(sender:)))
//singleTapGestureRecognizer.numberOfTapsRequired = 1
singleTapGestureRecognizer.cancelsTouchesInView = false
self.view.addGestureRecognizer(singleTapGestureRecognizer)
}
#objc func singleTap(sender: UITapGestureRecognizer) {
self.searchController.isActive = false
self.searchController.searchBar.resignFirstResponder()
self.searchController.searchBar.endEditing(true)
}
EDIT:
I was thinking, maybe it's because my searchBar and searchController aren't in the UIViewController's view hierarchy, but more in the NavigationController one.
So I also tried with :
navigationController?.view.endEditing(true)
I then was thinking, maybe it's because the UIScrollView within my UICollectionView is catching the tap.
So I tried to link the tap gesture on the UICollectionView instead of the UIView, but without success.
There is no need to add UITapGestureRecognizer as proposed above. UIViewContoller already conforms to UIResponder interface (legacy from Objective C), so you can override this method like this:
extension UIViewController {
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
self.view.window?.endEditing(true)
super.touchesEnded(touches, with: event)
}
}
Please create UIViewController for dismiss keyboard througout application.
extension UIViewController {
func hideKeyboardWhenTappedAround() {
let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(UIViewController.dismissKeyboard))
tap.cancelsTouchesInView = false
view.addGestureRecognizer(tap)
}
#objc func dismissKeyboard() {
view.endEditing(true)
}
}
Use above code in your UIViewController file as below.
override func viewDidLoad() {
super.viewDidLoad()
self.hideKeyboardWhenTappedAround()
}
Update:
You can also use below code to dismiss keyboard from any class.
UIApplication.shared.sendAction(#selector(UIResponder.resign‌​FirstResponder), to: nil, from: nil, for: nil)
Try the solution from Dimple Desai but add the gesture recognizer to the TableView or CollectionView or whatever is laying on top of your UIView. Then it should work.
override func viewDidLoad(){
let tapView = UITapGestureRecognizer(target: self, action: #selector(self.hideKeyboard))
self.view.addGestureRecognizer(tapView)
}
#objc func hideKeyboard(tap: UITapGestureRecognizer){
self.view.endEditing(true)
}
Is there any way i can pass parameters with UITapGestureRecognizer?
I've seen this answered for objective-c but couldn't find an answer for swift
test.userInteractionEnabled = true
let tapRecognizer = UITapGestureRecognizer(target: self, action: Selector("imageTapped4:"))
// Something like text.myParamater
test.addGestureRecognizer(tapRecognizer)
And then receive myParameter under func imageTapped4(){}
One approach would be to subclass UITapGestureRecognizer and then set a property, I've posted an example below. You could also do some check on the sender and check if equal to some tag, class, string, e.t.c
class ViewController: UIViewController {
#IBOutlet weak var label1: UILabel!
#IBOutlet weak var image: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
image.userInteractionEnabled = true;
let tappy = MyTapGesture(target: self, action: #selector(self.tapped(_:)))
image.addGestureRecognizer(tappy)
tappy.title = "val"
}
func tapped(sender : MyTapGesture) {
print(sender.title)
label1.text = sender.title
}
}
class MyTapGesture: UITapGestureRecognizer {
var title = String()
}
There are lots of examples on SO, have a look, good luck.
For Swift 4
In Viewdidload
let label = UILabel(frame: CGRect(x: 0, y: h, width: Int(self.phoneNumberView.bounds.width), height: 30))
label.textColor = primaryColor
label.numberOfLines = 0
label.font = title3Font
label.lineBreakMode = .byWordWrapping
label.attributedText = fullString
let phoneCall = MyTapGesture(target: self, action: #selector(self.openCall))
phoneCall.phoneNumber = "\(res)"
label.isUserInteractionEnabled = true
label.addGestureRecognizer(phoneCall)
Function as
#objc func openCall(sender : MyTapGesture) {
let number = sender.phoneNumber
print(number)
}
Write Class as
class MyTapGesture: UITapGestureRecognizer {
var phoneNumber = String()
}
Follow Step Properly and make change according to your variable , button ,label . It WORKS PROPERLY
Without subclassing, you can also add the parameter in the view layer (where the gesture is attached):
let tappy = UITapGestureRecognizer(target: self, action: #selector(self.tapped(_:)))
image.addGestureRecognizer(tappy)
image.layer.setValue(title, forKey: "anyKeyName")
Later in the handler
#objc private func tapped(_ sender: UIGestureRecognizer) {
guard let title = sender.view?.layer.value(forKey: "anyKeyName") as? String else { return }
// Do something with the title
}
The best way is to determind the parameter when the func imageTapped64is fired. You can get you params via the view (take a look to #Developer Sheldon answer)
or in many other ways.
I am trying long press Gesture in Swift for Copy Option.
But it is not working. It is not identifying the Gesture in UiView Or UILabel either.
Below is my Code
In View DidLoad
let copyLongPress = UILongPressGestureRecognizer(target: self, action: #selector(ContactDetailController.handleLongPress(_:)))
copyLongPress.numberOfTouchesRequired = 0
copyLongPress.delegate = self
copyLongPress.minimumPressDuration=0.5
self.lblDynaMobile.addGestureRecognizer(copyLongPress)
self.lblDynaMobile.userInteractionEnabled = true
self.lblDynaDDI.addGestureRecognizer(copyLongPress)
self.lblDynaDDI.userInteractionEnabled = true
self.GeneralView.addGestureRecognizer(copyLongPress)
self.EmailView.addGestureRecognizer(copyLongPress)
self.AddressView.addGestureRecognizer(copyLongPress)
New Mothod
func handleLongPress(longPressView :UILongPressGestureRecognizer) {
let lblFont:UILabel = (longPressView.view as? UILabel)!
UIPasteboard.generalPasteboard().string = lblFont.text
}
I have added UIGestureRecognizerDelegate too in the Declaration of class
Try this, and see (it's working.)
// in viewDidLoad()
let copyLongPress = UILongPressGestureRecognizer(target: self, action: #selector(self.handleLongPress(_:)))
self.lblDynaMobile.addGestureRecognizer(copyLongPress)
func handleLongPress(_ gesture: UILongPressGestureRecognizer) {
if let lblFont = gesture.view as? UILabel {
//UIPasteboard.generalPasteboard().string = lblFont.text
}
}
i have a test project that takes text from a file, adds it to a textview and displays it.
i want to add some gestures but cannot seem to make it work...
here is the relevant code:
class ViewController2: UIViewController, UIGestureRecognizerDelegate {
#IBOutlet var textview1: UITextView!
var pinchGesture = UIPinchGestureRecognizer()
override func viewDidLoad() {
super.viewDidLoad()
self.textview1.userInteractionEnabled = true
self.textview1.multipleTouchEnabled = true
self.pinchGesture.delegate = self
self.pinchGesture = UIPinchGestureRecognizer(target: self, action: #selector(ViewController2.pinchRecognized(_:)))
self.view.addGestureRecognizer(self.pinchGesture)
}
#IBAction func pinchRecognized(pinch: UIPinchGestureRecognizer) {
self.textview1.addGestureRecognizer(pinchGesture)
self.textview1.transform = CGAffineTransformScale(self.textview1.transform, pinch.scale, pinch.scale)
pinch.scale = 1.0
}
any ideas? followed several tutorials but none seem to help. code is tested on actual iPhone...
thanks a lot
Edit for Solution:
#IBAction func pinchRecognized(pinch: UIPinchGestureRecognizer) {
var pinchScale = pinchGesture.scale
pinchScale = round(pinchScale * 1000) / 1000.0
if (pinchScale < 1) {
self.textview1.font = UIFont(name: self.textview1.font!.fontName, size: self.textview1.font!.pointSize - pinchScale)
pinchScale = pinchGesture.scale
} else {
self.textview1.font = UIFont(name: self.textview1.font!.fontName, size: self.textview1.font!.pointSize + pinchScale)
pinchScale = pinchGesture.scale
}
}
thanks to nishith Singh
Try adding the gesture recogniser to your textview in viewDidLoad instead of adding it in pinchRecognized. Currently you are adding the pinchGesture to your view which is behind your text view and hence will not receive the touch
var pinchGesture = UIPinchGestureRecognizer()
Use this code:
override func viewDidLoad() {
super.viewDidLoad()
self.textview1.userInteractionEnabled = true
self.textview1.multipleTouchEnabled = true
self.pinchGesture = UIPinchGestureRecognizer(target: self, action:#selector(pinchRecognized(_:)))
self.textview1.addGestureRecognizer(self.pinchGesture)
// Do any additional setup after loading the view.
}
#IBAction func pinchRecognized(_ pinch: UIPinchGestureRecognizer) {
let fontSize = self.textview1.font!.pointSize*(pinch.scale)/2
if fontSize > 12 && fontSize < 32{
textview1.font = UIFont(name: self.textview1.font!.fontName, size:fontSize)
}
}
You might have to hit and trial with the minimum and maximum font sizes as you want, right now the minimum font size is 12 and the maximum font size is 32.
let pinchGesture = UIPinchGestureRecognizer(target: self, action:#selector(self.pinchGesture))
func pinchGesture(sender: UIPinchGestureRecognizer){
sender.view?.transform = (sender.view?.transform)!.scaledBy(x: sender.scale, y: sender.scale)
sender.scale = 1
print("pinch gesture")
}
class ViewController2: UIViewController, UIGestureRecognizerDelegate {
#IBOutlet var textview1: UITextView!
var pinchGesture = UIPinchGestureRecognizer()
override func viewDidLoad() {
super.viewDidLoad()
self.textview1.userInteractionEnabled = true
self.textview1.multipleTouchEnabled = true
self.pinchGesture.delegate = self
self.pinchGesture = UIPinchGestureRecognizer(target: self, action: "pinchRecognized:")
self.view.addGestureRecognizer(self.pinchGesture)
}
func pinchRecognized(pinch: UIPinchGestureRecognizer) {
self.textview1.addGestureRecognizer(pinchGesture)
self.textview1.transform = CGAffineTransformScale(self.textview1.transform, pinch.scale, pinch.scale)
pinch.scale = 1.0
}
Your code is actually working. But not the way you want probably.
Initially you assigned the gesture recogniser to the view of view controller.
But then inside the method you added same gesture recogniser to the UITextView.
So it should be working on UITextView. And the gesture recogniser is removed from the view controller's view. Gesture recogniser can only have one target. Pick view controller's view or textview.
You set the delegate of self.pinchGesture before initialising.
Initialise the self.pinchGesture first.
Set the delegate.
Add self.pinchGesture to self.view
self.pinchGesture.delegate = self
self.pinchGesture = UIPinchGestureRecognizer(target: self, action:#selector(ViewController2.pinchRecognized(_:)))
self.view.addGestureRecognizer(self.pinchGesture)
I attached events to my UIImageViews with UITapGestureRecognizer
override func viewDidLoad() {
super.viewDidLoad()
let cupPicture1Tap = UITapGestureRecognizer(target:self, action:Selector("imageTapped:"))
cupPicture1.userInteractionEnabled = true
cupPicture1.addGestureRecognizer(cupPicture1Tap)
let cupPicture2Tap = UITapGestureRecognizer(target:self, action:Selector("imageTapped:"))
cupPicture2.userInteractionEnabled = true
cupPicture2.addGestureRecognizer(cupPicture2Tap)
let cupPicture3Tap = UITapGestureRecognizer(target:self, action:Selector("imageTapped:"))
cupPicture3.userInteractionEnabled = true
cupPicture3.addGestureRecognizer(cupPicture3Tap)
}
func cupImageTapped(recognizer:UIPanGestureRecognizer) {
var clickedImageView: UIImageView = recognizer.view
let myPickerController = UIImagePickerController()
myPickerController.delegate = self;
myPickerController.sourceType = UIImagePickerControllerSourceType.Camera
myPickerController.allowsEditing = true
self.presentViewController(myPickerController, animated: true, completion: nil)
}
But i can't access which UIImageView clicked at cupImageTapped function. I am getting: "Cannot convert value of type 'UIView?' to specified type 'UIImageView'"
#IBOutlet var imageView: UIImageView!
#IBOutlet var MyImageView: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
// create tap gesture recognizer
let tapGesture = UITapGestureRecognizer(target: self, action: "tapGesture:")
// add it to the image view;
imageView.addGestureRecognizer(tapGesture)
// make sure imageView can be interacted with by user
imageView.userInteractionEnabled = true
}
func tapGesture(gesture: UIGestureRecognizer) {
// if the tapped view is a UIImageView then set it to imageview
if let imageView = gesture.view as? UIImageView { // if you subclass UIImageView, then change "UIImageView" to your subclass
// change the image on the MyImageView
MyImageView.image = imageView.image
// if you subclass UIImageView, then you could get the filename here.
}
}
This will work
You need to cast it to UIImageView
if var clickedImageView = recognizer.view as? UIImageView{
//Use clickedImageView here
}