UIImageview click not working - ios

I am very new to swift. I am implementing the functionality for click event for UIIMageview. My Code is below.
override func viewDidLoad() {
super.viewDidLoad()
initialize()
let logout = UIImage(named: "logout.png")
let location = UIImage(named:"location.png")
let appIcon = UIImage(named: "logo.png")
imgLogout.image = logout
imgLocation.image = location
appicon.image = appIcon
// Do any additional setup after loading the view, typically from a nib.
imgLogout.isUserInteractionEnabled = true
let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(ProductListController.profileImageHasBeenTapped(gesture:)))
//this is where we add the target, since our method to track the taps is in this class
//we can just type "self", and then put our method name in quotes for the action parameter
//finally, this is where we add the gesture recognizer, so it actually functions correctly
imgLogout.addGestureRecognizer(tapGestureRecognizer)
}
func profileImageHasBeenTapped(gesture: UIGestureRecognizer){
print("Triggered")
}
my click event is not triggered. Any body can help me from this.
Any will be appreciated.
XCode version is 8.3.3
Swift version is 3.1

Why not using a UIButton, that is designed for that kind of usage ?
let logout = UIButton(type: .custom)
logout.setImage(UIImage(named: "logout.png"), forState: .normal)
logout.addTarget(self, action: #selector(self.performLogout), for: .touchUpInside)
#objc
func performLogout() {
// Do something
}

It seems like yourchildview not in the front so try it:
yourparentview.bringSubview(toFront: imgLogout)

imageLogOut frame may be out of super view's bounds, please check it.use
self.profileImageHasBeenTapped(gesture:)
instead of
ProductListController.profileImageHasBeenTapped(gesture:)

set user interaction enabled for the image.
// for creating tap gesture recognizer
#IBOutlet weak var imageView: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
// create tap gesture recognizer
let tapGesture = UITapGestureRecognizer(target: self, action: "imageTapped:")
// add it to the image view;
imageView.addGestureRecognizer(tapGesture)
// make sure imageView can be interacted with by user
imageView.userInteractionEnabled = true
//if tap is not working bring image to front view
self.view.bringSubview(imageView)
}
func imageTapped(gesture: UIGestureRecognizer) {
// if the tapped view is a UIImageView then set it to imageview
if let imageView = gesture.view as? UIImageView {
println("Image Tapped")
//Here you can initiate your new ViewController
}
}
}

Related

How to detect longpress in BarButtonitem

I have a UIBarButtonItem in navigation bar. When a user clicks it, it pops to another viewController.
Now i want that when user long-press on that button (navigation bar button) I want to show a help message.
I want help to detect the onlick event and longpress event separately.
You should create a button and set UITapGestureRecognizer & UILongPressGestureRecognizer to your button
// Create a button
let yourButton = UIButton()
yourButton.backgroundColor = .red
yourButton.setTitle("long press", for: .normal)
// Create a tap gesture recognizer
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(didTap))
// Create a long gesture recognizer
let longGesture = UILongPressGestureRecognizer(target: self, action: #selector(long))
// You can set minimum duration of the press action
longGesture.minimumPressDuration = 3 //The default duration is 0.5 seconds.
// Add your gestures to button
yourButton.addGestureRecognizer(longGesture)
yourButton.addGestureRecognizer(tapGesture)
navigationItem.leftBarButtonItem = UIBarButtonItem(customView: yourButton)
#objc private func didTap() {
print("Did Tap")
}
#objc private func long() {
// You can show the help message in here
print("Long press")
}
try this in view didload:
let back = UIImage(named: "header_backarrow")
let backView = UIImageView(image: back)
backView.isUserInteractionEnabled = true
let tap = UITapGestureRecognizer(target: self, action: #selector(dismissManual))
backView.addGestureRecognizer(tap)
let backItem = UIBarButtonItem(customView: backView)
navigationItem.leftBarButtonItem = backItem
In the viewDidAppear of your view controller you can add this :
let gestureRecognizer = UILongPressGestureRecognizer(target: self, action: #selector(myCalledFunction))
(myUIBarButton.value(forKey: "view") as? UIView)?.addGestureRecognizer(gestureRecognizer)
This is difficult because UIBarButton doesn't really expose its view and so you cannot directly add a gestureRecognizer to it.
You can however get a reference to its view by using the value(forKey:) method and then play with it.
Do not do this in the viewDidLoad as it is necessary for the view to have already been created in order for this to work.
All of the other answers require implementing a UIBarButtonItem(customView:) to achieve this. However this can be implemented with any UIBarButtonItem instance without implementing your own gesture recognizer code.
An #IBAction can actually be passed a second parameter containing the UIEvent triggering the action. For example, instead of defining -
#objc func doSomething(sender: UIBarButtonItem) {
}
We can define -
#objc func doSomething(sender: UIBarButtonItem, forEvent event: UIEvent) {
guard let touch = event.allTouches?.first else { return }
if touch.tapCount == 1 {
// Handle tap
} else if touch.tapCount == 0 {
// Handle long press
}
}
Source : http://li366-68.members.linode.com/2016/09/07/detecting-long-presses-on-uibarbuttonitems.html
so I found that UIBarButton has not property like longpress so all I do is take a UIButton give it longpress gesture and add that UIButton in navigation bar as UIBarButtonItem.
I hope it will helpful for someone else who is facing same problem.
let btn = UIButton(frame: CGRect(x: 0, y: 0, width: 40, height: 40))
btn.backgroundColor = .green
let gesture = UILongPressGestureRecognizer(target: self, action: #selector(longpress))
btn.addGestureRecognizer(gesture)
let barbtn = UIBarButtonItem(customView: btn)
self.navigationItem.rightBarButtonItem = barbtn
thank you :)

UILabel set onClick

I'm building an application in Swift 3, so I want to call a function if I click on a particular UILabel, so I'm write this code but not works:
let tap = UITapGestureRecognizer(target: self, action: #selector(ViewController.tapFunction))
self.labelTemp.isUserInteractionEnabled = true
self.labelTemp.addGestureRecognizer(tap)
How can I render UILabel clickable ?
Set user interaction enabled for the UILabel and add the below code in the viewDidLoad()
self.label.isUserInteractionEnabled = true
let tap = UITapGestureRecognizer(target: self, action: #selector(self.labelTapped))
self.label.addGestureRecognizer(tap)
Add the tap action function as below :
#objc func labelTapped(_ gestureRecognizer: UITapGestureRecognizer) {
print("Label clicked")
}
Please make user that there is no other transparent view overlapping the UILabel in the view. If the UILabel is a part of another view then please make sure that the container View's user interaction is enabled.
Hope this helps.
Your selector should be an #objc func within self.
<#YourLabel#>.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(self.handleLabelTap)))
And when the user taps the label it will trigger:
#objc func handleLabelTap() {
// handle label tap here
}
You are lacking a function to trigger when the gesture touch is recognized. You need to add following:
let tap = UITapGestureRecognizer(target: self, action: #selector(tapFunction(_:)))
self.labelTemp.isUserInteractionEnabled = true
self.labelTemp.addGestureRecognizer(tap)
#objc func tapFunction(_ gestureRecognizer: UITapGestureRecognizer) {
// handle label tap here
}
Please ensure that You have connected the outlet to UILabel because I have created simple demo code by copy-paste your code and it is worked as expected.
override func viewDidLoad() {
super.viewDidLoad()
let tap = UITapGestureRecognizer(target: self, action: #selector(tapFunction))
self.labelTemp.isUserInteractionEnabled = true
self.labelTemp.addGestureRecognizer(tap)
}
#objc func tapFunction() {
print("tapFunction")
}
I suggest, Please remove UILabel from UIViewController and add it again.
Download sample code
Note: - Please ensure that user-interaction of UILabelis enabled
First you need to add Tap Gesture into storyboard
Create Action of that particular gesture
override func viewDidLoad() {
super.viewDidLoad()
let tapOnLabel = UITapGestureRecognizer(target: self, action: #selector(self.tapGestireAction))
self.labelTemp.isUserInteractionEnabled = true
self.labelTemp.addGestureRecognizer(tapOnLabel)
}
#IBAction func tapGestureAction(_ sender: UITapGestureRecognizer) {
//Perform action
}

How to add an action for when an image is clicked? [duplicate]

This question already has answers here:
How do you make an UIImageView on the storyboard clickable (swift)
(9 answers)
Closed 4 years ago.
I am trying to use a custom image as a button in my app. How do I add an action for an image?
This is for an iOS app and I don't want to use the default text button as a button. I've already tried control+dragging the image to the ViewController but there is no "Action" option.
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let designChoice = designPrac.randomElement()
let forChoice = forWhatPrac.randomElement()
let helpChoice = toHelpPrac.randomElement()
designLabel.text = designChoice
forLabel.text = forChoice
helpLabel.text = helpChoice
}
This is the code I have to run when the app launches but I can't find a way to get this to work for when my image button is clicked.
In order to add an action to an UIImageView, you need to add a UITapGestureRecognizer to it, you can do it like this:
<#YourImageView#>.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(self.handleImageTap)))
Then you can handle the tap using the selector:
#objc func handleImageTap() {
// handle image tap here
}
You can use addGestureRecognizer for this purpose:
let imageView = UIImageView()
//add necessary code
imageView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(MethodForAction)))
According to How do you make an UIImageView on the storyboard clickable (swift):
class ViewController: UIViewController {
#IBOutlet weak var imageView: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
// create tap gesture recognizer
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(ViewController.imageTapped(gesture:)))
// add it to the image view;
imageView.addGestureRecognizer(tapGesture)
// make sure imageView can be interacted with by user
imageView.isUserInteractionEnabled = true
}
func imageTapped(gesture: UIGestureRecognizer) {
// if the tapped view is a UIImageView then set it to imageview
if (gesture.view as? UIImageView) != nil {
print("Image Tapped")
//Here you can initiate your new ViewController
}
}

How can we add a UIGestureRecognizer to Outlet Collection?

I'm trying to add a tap gesture to an outlet collection of labels [UILabel], like this:
#IBOutlet var subLabels: [UILabel]!
override func viewDidLoad() {
super.viewDidLoad()
let tap = UITapGestureRecognizer(target: self, action: #selector(HomePageViewController.selectSubLabel(tap:)))
tap.numberOfTapsRequired = 1
tap.cancelsTouchesInView = false
for i in (0..<(subLabels.count)) {
subLabels[i].addGestureRecognizer(tap)
}
}
func selectSubLabel(tap: UITapGestureRecognizer) {
print("Gesture Is WORKING!")
}
and i tried to add it on a single label in storyboard; but NONE are working.
Firstly, you need to allow user interaction on a label (it is turned off by default):
for i in (0..<(subLabels.count)) {
subLabels[i].isUserInteractionEnabled = true
subLabels[i].addGestureRecognizer(tap)
}
but gesture recognizer can observe for gestures only in one view.
So, there are two options:
I. Dedicated gesture recognizer for every label
for i in (0..<(labels.count)) {
let tap = UITapGestureRecognizer(target: self, action: #selector(selectSubLabel(tap:)))
labels[i].isUserInteractionEnabled = true
labels[i].addGestureRecognizer(tap)
}
II. One gesture recognizer for the parent view of the labels
override func viewDidLoad() {
super.viewDidLoad()
for i in (0..<(labels.count)) {
subLabels[i].isUserInteractionEnabled = true
}
let tap = UITapGestureRecognizer(target: self, action: #selector(selectSubLabel(tap:)))
view.addGestureRecognizer(tap)
}
func selectSubLabel(tap: UITapGestureRecognizer) {
let touchPoint = tap.location(in: view)
guard let label = subLabels.first(where: { $0.frame.contains(touchPoint) }) else { return }
// Do your stuff with the label
}
Please check the User Interaction Enabled Attribute of your UIlabel's in Attribute inspector of Xcode. User Interaction Enabled must be ticked for detecting the tap. Please see the picture below,

How can I detect which custom button was tapped in a bank of custom buttons in ios

I have a bank of 6 custom buttons which I implemented using images with user interaction enabled. I also added a tag to each switch. I attached a tap gesture recognizer to each button. I used a techniques described in
detect view was tapped
When I press any of the buttons I always get the last button that the gesture was attached to. Here is the code. Help would be appreciated.
import UIKit
class HomeViewController: UIViewController {
#IBOutlet var buttonImages: [UIImageView]!
var selectedOption = 0
#IBAction func tapped(sender: UITapGestureRecognizer) {
let buttonImage = sender.view!
println("Tag: \(buttonImage.tag) image: \(buttonImage)")
selectedOption = (sender.view?.tag)!
println("tapped: \(selectedOption)")
}
override func viewDidLoad() {
super.viewDidLoad()
let tapGestureRecognizer = UITapGestureRecognizer(target: self,
action: "tapped:")
tapGestureRecognizer.numberOfTouchesRequired = 1
tapGestureRecognizer.numberOfTapsRequired = 1
let x = UIImage(named:"TV normal.png") // replace with array
var tag = 0
for buttonImage in buttonImages {
buttonImage.addGestureRecognizer(tapGestureRecognizer)
buttonImage.image = x
buttonImage.tag = tag
tag++
}
// check
for buttonImage in buttonImages {
println("Tag: \(buttonImage.tag) image: \(buttonImage)")
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
Your issue is due to the fact you are attaching the same UITapGestureRecognizer for each UIImage, but a gesture can be attached to only one UIView at the same time, that's why you always getting back the last one.
In your case, you just need to create a new UITapGestureRecognizer for each UIImage you are creating with the same target / action. This way, your method tapped will work.

Resources