I have a tap gesture that runs this code and it works once but then stops updating the zoomScale.
#objc func sampleTapGestureTapped(_ recognizer: UITapGestureRecognizer) {
print("tapped")
if self.scrollView_Image.zoomScale > self.scrollView_Image.minimumZoomScale {
scrollView_Image.setZoomScale(1, animated: false)
} else {
scrollView_Image.setZoomScale(3, animated: false)
}
}
The function runs and the tapped print is logged out but the zoomScale doesn't seem to change.
Perhaps the problem is your hard coded numbers. Here is how I do it:
if sv.zoomScale < sv.maximumZoomScale {
sv.setZoomScale(sv.maximumZoomScale, animated:anim)
}
else {
sv.setZoomScale(sv.minimumZoomScale, animated:anim)
}
Notice there are no hard coded numbers here. It works for any scroll view.
I've tried this in a small View Controller and it is working fine. It is possible that an action you are taking in the selector is stopping the gesture from working. You should probably post the selector function code as well, and anything relevant to setting up the Recognizer and the Image View
class ViewController: UIViewController {
var tappableImageView: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
tappableImageView = UIImageView(frame: CGRect(x: 40, y: 40, width: 100, height: 100))
tappableImageView.backgroundColor = .red
view.addSubview(tappableImageView)
tappableImageView.isUserInteractionEnabled = true
let t = UITapGestureRecognizer(target: self, action: #selector(imageViewDoubleTapped(_:)))
t.numberOfTapsRequired = 2
tappableImageView.addGestureRecognizer(t)
}
#objc func imageViewDoubleTapped(_ recognizer: UITapGestureRecognizer) {
print("Double Tapped")
}
}
Related
I have developed a UIView from For loop and basically it is create 3 Views from loop. and I have to add touch gesture on every View to call a method but I am unable to get current selected UIView.tag when I tap on it. it is only showing the .tag of the last view. here is my code.
for i in 0 ... 2 {
let productView = UIView()
productView.tag = i
productView.isUserInteractionEnabled = true
let producttap = UITapGestureRecognizer(target: self, action: #selector(self.ProductTapped))
productView.addGestureRecognizer(producttap)
productView.frame = CGRect(x: xOffset, y: CGFloat(buttonPadding), width: 200, height: scView1.frame.size.height)
xOffset = xOffset + CGFloat(buttonPadding) + productView.frame.size.width
scView1.addSubview(productView)
productIndex = productView.tag
}
and here is the method that I am calling from every UIView touch.
#objc func ProductTapped() {
print("",productIndex)
}
Your code should be using delegate/callback closure, but if you want to keep using tag, try change it to:
#objc func ProductTapped(_ sender: UITapGestureRecognizer) {
if let view = sender.view {
print(view.tag)
}
}
and the gesture attach to let producttap = UITapGestureRecognizer(target: self, action: #selector(self.ProductTapped(_:)))
productIndex does nothing here since it got overwritten on the loop
productIndex currently has no relationship to the tap gestures that you attach your views. You do set productIndex in the the loop but that's irrelevant to your gesture.
Perhaps you want
let producttap = UITapGestureRecognizer(target: self, action: #selector(productTapped(_:))
and
#objc func productTapped(_ gesture: UITapGestureRecognizer) {
print("tag is",gesture.view.tag)
}
I have an Intro video section for an app. The storyboard has a segue "toMainMenu" that links to another storyboard view controller.
The IntroVideoVC has two classes inside it:-
class IntroVideoVC: UIViewController {
var videoView: IntroVideoView!
override func viewDidLoad() {
videoView = IntroVideoView(controller: self)
self.view.addSubview(videoView)
let tap = UITapGestureRecognizer(target: self, action: #selector(tappedVideo))
view.addGestureRecognizer(tap)
}
#objc func tappedVideo() {
videoFinished();
}
func videoFinished() {
self.performSegue(withIdentifier: "toMainMenu", sender: self)
}
}
class IntroVideoView: UIView {
init(controller: UIViewController) {
super.init(frame: CGRect(x: 0, y: 0, w: 0, h: 0))
self.controller = controller
...
}
func handleVideo(videoPlayer: AVPlayer) {
...
IntroVideoVC().videoFinished()
}
}
If i tap the video it correctly performs the segue, however if i let the video end which in-turn calls IntroVideoViews -> handleVideo() method i get a crash stating it has no segue with identifier "toMainMenu".
I think i understand why but unsure how to get around the issue being new to swift. I believe it is because handleVideo() is using IntroVideoVC as a singleton and so is losing reference to IntroVideoVC's controller! I maybe (read: likely) be wrong but that is what i feel may be causing this issue.
Just looking for a nudge in the right direction
thanks in advance
You could use protocol to solve that, it would be something like this:
protocol IntroVideoDelegate {
func videoFinished()
}
class IntroVideoVC: UIViewController, IntroVideoDelegate {
var videoView: IntroVideoView!
override func viewDidLoad() {
videoView = IntroVideoView(controller: self)
videoView.videoDelegate = self
self.view.addSubview(videoView)
let tap = UITapGestureRecognizer(target: self, action: #selector(tappedVideo))
view.addGestureRecognizer(tap)
}
#objc func tappedVideo() {
videoFinished();
}
func videoFinished() {
self.performSegue(withIdentifier: "toMainMenu", sender: self)
}
}
class IntroVideoView: UIView {
videoDelegate: IntroVideoDelegate?
init(controller: UIViewController) {
super.init(frame: CGRect(x: 0, y: 0, w: 0, h: 0))
self.controller = controller
...
}
func handleVideo(videoPlayer: AVPlayer) {
...
videoDelegate.videoFinished()
}
}
Remember that the videoView is still a subview to IntroVideoVC, so if the app goes back to this VC the user will see it, so if you don't want that to happen, be sure to remove it with:
videoView.removeFromSuperview()
In the videoFinished() func
If you want to do running a VC func from the view you should get the parent of IntroVideoView, here is how: Given a view, how do I get its viewController? But i'm pretty sure it breaks MVC
The code below compiles fine, but crashes with an unrecognized selector sent to instance error.
I have one class that inherits from UIViewController:
class Controller: UIViewController {
override func viewDidLoad() {
let toolbarWrapper = CustomToolbarWrapper(view: view, target: self)
let toolbar = toolbarWrapper.toolbarView
view.addSubview(toolbar)
... Other code ...
}
}
And another class that is just a wrapper for a UIView and contains buttons:
class CustomToolbarWrapper {
var toolbarView: UIView
init(view: UIView, target: Any) {
let height: CGFloat = 80
toolbarView = UIView(frame: CGRect(x: 0, y: view.frame.height - height, width: view.frame.width, height: height))
let button = UIButton()
... Some button layout code ...
button.addTarget(target, action: #selector(CustomToolbar.buttonTapped(_:)), for: .touchUpInside)
toolbarView.addSubview(button)
}
#objc static func buttonTapped(_ sender: Any) {
print("button tapped")
}
}
For the sake of clarity, I left out a large chunk of code and kept what I thought was necessary. I think that my code doesn't work because of my misunderstanding of the how the target works in the addTarget function. Normally, I would just use self as the target of my button's action, so I just tried to pass along self from the view controller to the CustomToolbarWrapper's init function.
What else I have tried:
Changing the button's target from target to self like this:
button.addTarget(self, action: #selector(CustomToolbar.buttonTapped(_:)), for: .touchUpInside)
results in the app not crashing anymore. Instead, however, I believe that line of code fails to do anything (which doesn't throw an error for some reason?) because attempting to print button.allTargets or even button.allTargets.count results in the app crashing at compile time, with an EXC_BREAKPOINT error and no error description in the console or the XCode UI (which just confuses me even more because there are no breakpoints in my code!).
Also, making buttonPressed(_:) non-static does not change any of the previously mentioned observations.
Also, to make sure the button could in fact be interacted with, I added this in the viewDidLoad() of Controller:
for subview in toolbar.subviews? {
if let button = subview as? UIButton {
button.addTarget(self, action: #selector(buttonPressed(_:)), for: .touchUpInside)
}
}
and added a simple testing method to Controller for the button:
#objc func buttonPressed(_ sender: UIButton) {
print("Button Pressed")
}
And running the code did result in "Button Pressed" being printed in the console log, so the button should be able to be interacted with by the user.
Feel free to let me know if you think this is not enough code to figure out the problem, and I will post more details.
Edit
I prefer to keep the implementation of the button's action in the CustomToolbarWrapper class to prevent repeating code in the future, since the action will be the same no matter where an instance of CustomToolbarWrapper is created.
The best option would be to add the target in your controller and then call a method in your toolbarWrapper on button press. But if you really need to keep this design, you should have a strong reference to your toolbarWrapper in your controller class, otherwise your toolbarWrapper is deallocated and nothing gets called. Also, the buttonTapped(_:) method does not need to be static. Thus, in your controller:
class Controller: UIViewController {
var toolbarWrapper: CustomToolbarWrapper?
override func viewDidLoad() {
toolbarWrapper = CustomToolbarWrapper(view: view, target: self)
let toolbar = toolbarWrapper.toolbarView
view.addSubview(toolbar)
... Other code ...
}
}
And in your wrapper:
class CustomToolbarWrapper {
var toolbarView: UIView
init(view: UIView, target: Any) {
let height: CGFloat = 80
toolbarView = UIView(frame: CGRect(x: 0, y: view.frame.height - height,width: view.frame.width, height: height))
let button = UIButton()
... Some button layout code ...
button.addTarget(self, action: #selector(buttonTapped(_:)), for: .touchUpInside)
toolbarView.addSubview(button)
}
#objc func buttonTapped(_ sender: Any) {
print("button tapped")
}
}
There is another way I would use which is delegation. The target does not necessarily have to be a controller, it can be the CustomToolbarWrapper itself.
First, declare a protocol
protocol CTDelegate: AnyObject {
func didClickButton()
}
Then in CustomToolbarWrapper add a property, weak var delegate: CTDelegate? and a button action:
#objc func buttonTapped(_ sender: UIButton) {
delegate?.didClickButton()
}
So in your case, it becomes:
button.addTarget(self, action: #selector(CustomToolbarWrapper.buttonTapped(_:)), for: .touchUpInside)
Then when you go to any ViewController, conform to CTDelegate and initialize the CustomToolbarWrapper, you can set its delegate to the controller.
e.g
let toolbarWrapper = CustomToolbarWrapper(view: view, target: self)
toolbarWrapper.delegate = self
and implement your action inside the method you are conforming to in your controller i.e.
func didClickButton()
Your problem is right here:
let toolbarWrapper = CustomToolbarWrapper(view: view, target: self)
You're passing an instance of Controller class which doesn't implement the buttonTapped(_:) selector. It is implemented by your CustomToolbarWrapper class. This is a bad design in general. You should either follow a delegate pattern, or a callback pattern.
Updated Answer:
Delegate pattern solution:
class Controller: UIViewController, CustomToolbarWrapperDelegate {
override func viewDidLoad() {
let toolbarWrapper = CustomToolbarWrapper(view: view, buttonDelegate: self)
let toolbar = toolbarWrapper.toolbarView
view.addSubview(toolbar)
}
// MARK: - CustomToolbarWrapperDelegate
func buttonTapped(inToolbar toolbar: CustomToolbarWrapper) {
print("button tapped")
}
}
protocol CustomToolbarWrapperDelegate: AnyObject {
func buttonTapped(inToolbar toolbar: CustomToolbarWrapper) -> Void
}
class CustomToolbarWrapper {
var toolbarView: UIView
weak var buttonDelegate: CustomToolbarWrapperDelegate?
init(view: UIView, buttonDelegate: CustomToolbarWrapperDelegate?) {
let height: CGFloat = 80
toolbarView = UIView(frame: CGRect(x: 0, y: view.frame.height - height, width: view.frame.width, height: height))
self.buttonDelegate = buttonDelegate
let button = UIButton()
button.addTarget(self, action: #selector(self.buttonTapped(_:)), for: .touchUpInside)
toolbarView.addSubview(button)
}
#objc private func buttonTapped(_ sender: Any) {
// Your button's logic here. Then call the delegate:
self.buttonDelegate?.buttonTapped(inToolbar: self)
}
}
If you'd rather stick to your current design then just implement the following changes:
class Controller: UIViewController {
override func viewDidLoad() {
let toolbarWrapper = CustomToolbarWrapper(view: view, target: self, selector: #selector(self.buttonTapped(_:)), events: .touchUpInside)
let toolbar = toolbarWrapper.toolbarView
view.addSubview(toolbar)
}
#objc private func buttonTapped(_ sender: Any) {
print("button tapped")
}
}
class CustomToolbarWrapper {
var toolbarView: UIView
init(view: UIView, target: Any?, selector: Selector, events: UIControlEvents) {
let height: CGFloat = 80
toolbarView = UIView(frame: CGRect(x: 0, y: view.frame.height - height, width: view.frame.width, height: height))
let button = UIButton()
button.addTarget(target, action: selector, for: events)
toolbarView.addSubview(button)
}
}
I've got a UICollectionView that typically contains 100-200 cells that scrolls both horizontally and vertically. I am trying to provide a simple UIView popup with 3 icons when the user performs a LongPress gesture to allow them to easily navigate to a couple specific cells within the UICollectionView.
I'd like the start of the LongPress to bring up the popup, then the user would drag their finger to one of the three icons and release to select that icon.
The problem I'm having is I can't figure out how to get either the view containing the 3 icons or the icons themselves to respond to the end of the LongPress gesture.
Here's a simplification of the UIViewController:
class MyViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource {
#IBOutlet weak var myCollectionView: UICollectionView!
#IBAction func longTouch(_ sender: UILongPressGestureRecognizer) {
if sender.state == .began {
self.menu!.frame = CGRect(x: sender.location(in: self.view).x - 20,
y: sender.location(in: self.view).y - 75,
width: 100, height: 100)
self.menu!.isHidden = false
}
else if sender.state == .ended {
self.menu!.isHidden = true
}
}
// Popup for long touch
var menu: UIView?
// MARK: UIViewController
override func viewDidLoad() {
super.viewDidLoad()
self.initMenu()
}
// MARK:- UICollectionViewDelegate
...
// MARK:- UICollectionViewDataSource
...
// MARK:- UIScrollViewDelegate
...
private func initMenu() -> Void {
self.menu = UIView()
self.menu!.isUserInteractionEnabled = true
self.menu!.frame = CGRect(x: 0,
y: 0,
width: 100,
height: 50)
let longPress = UILongPressGestureRecognizer(target: self, action: #selector(menuLongPressHandler))
self.menu!.addGestureRecognizer(longPress)
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(handleTap(sender:)))
self.menu!.addGestureRecognizer(tapGesture)
// There would be ImageView icons here as well, which I've left out for simplicity
self.menu!.isHidden = true
}
func menuLongPressHandler() {
print("Long Press")
}
func handleTap(sender: UITapGestureRecognizer) {
print("Tap")
}
}
Neither the "Tap" or "Long Press" are printed when the LongPress ends while over the View. Any suggestions on how to get the view to capture the end of that LongPress gesture?
I have a custom class Overlay where I added UIButton. When the button is clicked, a method should be called:
class Overlay {
func show(onView view: UIView, frame: CGRect) {
let dismissButton = UIButton()
dismissButton.frame = frame
dismissButton.setTitle("Dismiss", for: .normal)
dismissButton.setTitleColor(Project.Color.failure, for: .normal)
dismissButton.titleLabel?.font = Project.Typography.lightFont.withSize(22)
view.addSubview(dismissButton)
dismissButton.isUserInteractionEnabled = true
let tap = UITapGestureRecognizer(target: self, action: #selector(dismissBtnTapped(tap:)))
dismissButton.addGestureRecognizer(tap)
}
#objc func dismissBtnTapped(tap: UITapGestureRecognizer) {
print("TEST")
}
I call show(...) inside my ViewController, passing in its view and a frame.
But the tapGestrueRecognizer is not working. Any ideas?
Thank you.
Edit: I tried putting this code directly inside my ViewController. Then it works. I'm not sure why, though, and that's not a viable solution for me, unfortunately :/
Edit 2:
That's how I call it:
let overlay = Overlay()
overlay.show(onView: self.view, frame: CGRect(x: 0, y: 0, width: view.bounds.width, height: 150))
You are already adding a button try adding a target to it instead of a gesture,
and make your overlay variable global.
class YourControllerClass: UIViewController {
let overlay = Overlay()
...
func show(onView: UIView, frame: CGRect) {
...
dismissButton.addTarget(self, action: #selector(dismissBtnTapped(_:)), forControlEvents: .TouchUpInside)
}
func dismissBtnTapped(sender:UIButton){
}
}
Hope this helps.
You not need to add tapgesturerecognizer on uibutton, you can directly add target on it something like,
dismissButton.addTarget(self, action: #selector(dismissBtnTapped), forControlEvents: .TouchUpInside)
and remove parameter from dismissBtnTapped method!
Make sure your view which you are passing as onView in show(onView: UIView, frame: CGRect) method is enabled for user interactions.
As an example my script
step 1
class MyIcon {
var targetController = UIViewController()
func show(_ targetController:UIViewController, _ view: UIView, _ frame: CGRect) {
self.targetController = targetController
let icon = UIImageView()
icon.frame = frame
icon.image = UIImage(named: "image_user.png")
icon.isUserInteractionEnabled = true
view.addSubview(icon)
let tap = UITapGestureRecognizer(target: self.targetController, action: #selector(iconTapped))
icon.addGestureRecognizer(tap)
}
#objc func iconTapped(_ icon: UIImageView) {
print("Yo hoo! This worked!")
}
}
step 2
class MyController: UIViewController{
let myicon = MyIcon()
override func viewDidLoad() {
super.viewDidLoad()
myicon.show(self, self.view, self.view.frame)
}
#IBAction func iconTapped(_ icon: UIImageView){
myicon.iconTapped(icon)
}
}
Non of the above solve the problem here.
The point is, if you create the instance of the custom class inside of an event the instance is deleted after the event is completed since it is not associated with any persistent element in your app. Thats why you have to instantiate the object of the class as an attribute of the superview.