UITapGestureRecognizer works first time, but not second time - swift

[Greatly simplified]
I'm following a "Let's Build That App" YouTube series on Firebase 3. It's from 2016, so I've had to rework some of the code since Swift has evolved since then, but mostly it's a useful tutorial.
But, I'm stuck on something.
The red box is intended to be a custom titleView with an Image and Name, but I've simplified it to try to find the problem.
viewWillAppear calls setupNavbar which sets up the navbar.titleView:
func setupNavbar() {
let titleView = UIView()
titleView.frame = CGRect(x: 0, y: 0, width: 300, height: 40)
titleView.backgroundColor = .red
let containerView = UIView() // for the Image and Label, later
containerView.translatesAutoresizingMaskIntoConstraints = false
containerView.backgroundColor = .green
// left, top, width, height anchors equal to same for titleView
containerView.leftAnchor.constraint(equalTo: titleView.leftAnchor)
// top, width, height are similar
titleView.addSubview(containerView)
self.navigationItem.titleView = titleView
let recognizer = UITapGestureRecognizer(target: self, action: #selector(showChatController))
titleView.addGestureRecognizer(recognizer)
}
The selector's function is:
#objc func showChatController() {
let chatController = ChatLogTableViewController()
navigationController?.pushViewController(chatController, animated: true)
}
The class ChatLogTableViewController has just the default viewDidLoad().
First, I'm surprised the box is red, and not green. Why is that?
Second, if I click the red box, the ChatController is loaded, as expected. But, when I click "Back" and return to this screen, the red box is not visible, thus I can no longer tap on it. BUT....If I sign out and sign in/up again, the box is red and I can click it again.
What am I missing?
Update 1: The "+" creates a new controller and presents it.
present(UINavigationController(
rootViewController: NewMessageTableViewController()),
animated: true,
completion: nil)
That controller is currently empty, except for a leftBarButtonItem which is just a barButtonSystemItem (.cancel). Just like "Sign Out", this also "resets" the gesture and it works.
Update 2: Code added upon request.
Update 3: question greatly simplified. Also, if I change the showChatController code to just print ("show Chat Controller"), I can click to my heart's content; the red box and its tap gesture both remain.
So, there is something happening when I ...pushViewController and then come back.

Have you tried to set isUserInteractionEnabled property of the label which you set as the navBar's titleView? I know it's silly but I've missed this a lot of times :)
let recognizer = UITapGestureRecognizer(target: self, action: #selector(YourViewController.titleWasTapped))
titleView.isUserInteractionEnabled = true
titleView.addGestureRecognizer(recognizer)

you can try following things:
1. "User Interaction Enabled" in the UILabel Attributes Inspector in the Storyboard.
2. override func viewDidLoad(animated: Bool) {
super.viewDidAppear(animated)
self.titleView.userInteractionEnabled = true
var tapGesture = titleView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(showChatController)))
self.titleView.addGestureRecognizer(tapGesture)
}
func showChatController() {
println("Tap Gesture recognized")
}

Hi #Zonker I've tested your setupNavBar(). It's working fine nothing worng with your code when I press and go back clicking titleView. Reason why you're not getting .green color is you have to give height and width for containerView and big reason is you've put addSubView code below the anchor and there is no .isActive = true in your containerView.leftAnchor.constraint... Please check setupNavBar() code below:
func setupNavbar() {
let titleView = UIView()
titleView.frame = CGRect(x: 0, y: 0, width: 300, height: 40)
titleView.backgroundColor = .red
let containerView = UIView() // for the Image and Label, later
containerView.translatesAutoresizingMaskIntoConstraints = false
containerView.backgroundColor = .green
titleView.addSubview(containerView)
// left, top, width, height anchors equal to same for titleView
containerView.widthAnchor.constraint(equalToConstant: 300).isActive = true
containerView.heightAnchor.constraint(equalToConstant: 40).isActive = true
containerView.leftAnchor.constraint(equalTo: titleView.leftAnchor).isActive = true
// top, width, height are similar
self.navigationItem.titleView = titleView
let recognizer = UITapGestureRecognizer(target: self, action: #selector(showChatController))
titleView.addGestureRecognizer(recognizer)
}
It would better if you push your code in github so we can test your code

Related

How can I add two images (one at the left and one on the right side) in a button in Xcode programaticly? I need also a title of a button

func setupButtonUI() {
if let detailsImage = UIImage(named: "detalji_icon") {
setImage(detailsImage, for: .normal)
contentHorizontalAlignment = .left
contentVerticalAlignment = .center
}
if let arrowImage = UIImage(named: "posalji_zahtev_black_icon") {
setImage(arrowImage, for: .normal)
contentHorizontalAlignment = .right
contentVerticalAlignment = .center
}
}/this is one of the things I tried, but whit this I get only the second image and its set in the center not right and the left image is hot even there/
UIButton has only one imageView, you can create custom button like in this answer
https://stackoverflow.com/a/43112735/13628690
Found the next solution: Made a custom UIView and added two images and label as a subview of customView. Did the constraints programaticly. Just added UITapGestureRecognizer (addGestureRecognizer) at the entire view and its all elements are clickable. The design and functionality are satisfied.

How to stretch title view in swift?

I created custom title view for UINavigationItem.
And I want custom view stretch to right padding.
What can I do??
I tried to set rightBarButtonItem to nil.
But it seems no solution.
And don't stretch to left backButton area.
override func viewDidLoad() {
super.viewDidLoad()
let searchBar = CustomSearchBar()
searchBar.autoresizingMask = .flexibleWidth
searchBar.frame = CGRect(x: 0, y: 0, width: 400, height: 30)
self.navigationItem.titleView = searchBar
self.navigationItem.rightBarButtonItem = UIBarButtonItem()
}
See my result. I want a red area.
https://imgur.com/a/dar3cMN
Try the following inside your CustomSearchBar class:
override var intrinsicContentSize: CGSize {
return UILayoutFittingExpandedSize
}
let searchBar = CustomSearchBar()
searchBar.translatesAutoresizingMaskIntoConstraints = false
self.navigationItem.titleView = searchBar
searchBar.heightAnchor.constraint(equalToConstant: 30.0).isActive = true
searchBar.rightAnchor.constraint(equalTo: self.navigationController!.navigationBar.rightAnchor).isActive = true
searchBar.leftAnchor.constraint(equalTo: self.navigationController!.navigationBar.centerXAnchor).isActive = true
The above code worked for me. You can remove the left anchor if you do not need the bar in the center. I also set the translatesAutoresizingMaskIntoConstraints to false, I hope this works.

UIStackView Animation Issue

I have a subStackView inside a stackView and when I hide/show the contents of ONE subStackView, the animation goes all the way up over the other stack views: https://www.youtube.com/watch?v=vKXwX7OpkxU
This is how I create the subStackView. I tried with and without clipToBounds and with an without translatedAutoresizingMaskIntoConstraints. Also tried layoutIfNeeded in the animation part.
let subStackView = UIStackView(arrangedSubviews: [self.innerView[0], self.innerView[1])
subStackView.translatesAutoresizingMaskIntoConstraints = false
subStackView.axis = .vertical
subStackView.distribution = .fillEqually
subStackView.alignment = .fill
subStackView.spacing = 0
subStackView.clipsToBounds = true
This subStackView is then loaded into a mainStackView which results in the issue.
One way to fix your problem is to control more directly how the purple view is shown and hidden. What you're doing now (I assume) is setting isHidden property to true and then letting the stack view do whatever it wants. Instead, let's put the purple view inside a container view, and animate the container view's height down to zero. Then it can look like this:
The reason to use a container view instead of just animating the purple view's height directly is that you might (in general) have other constraints controlling the purple view's height, so also constraining its height to zero would fill up your console with unsatisfiable constraint errors.
So here's what I did for the demo. I made a “Hello, world!” label with a purple background. I constrained its height to 80. I put the label inside a container view (just a plain UIView). I constrained the top, leading, and trailing edges of the label to the container view, as normal. I also constrained the bottom edge of the label to the container view, but at priority 999* (which is less than the default, “required” priority of 1000). This means that the container view will try very hard to be the same size as the label, but if the container view is forced to change height, it will do so without affecting the label's height.
The container also has clipsToBounds set, so if the container becomes shorter than the label, the bottom part of the label is hidden.
To toggle the visibility of the label, I activate or deactivate a required-priority height constraint on the container view that sets its height to zero. Then I ask the window to lay out its children, inside an animation block.
In my demo, I also have the stack view's spacing set to 12. If I just leave the container view “visible” (not isHidden) with a height of zero, the stack view will put 12 points of space after the button, which can look incorrect. On iOS 11 and later, I fix this by setting a custom spacing of 0 after the button when I “hide” the container, and restore the default spacing when I “show” it.
On iOS version before iOS 11, I just go ahead and really hide the container (setting its isHidden to true) after the hiding animation completes. And I show the container (setting its isHidden to false) before running the showing animation. This results in a little bump as the spacing instantly disappears or reappears, but it's not too bad.
Handling the stack view spacing makes the code substantially bigger, so if you're not using spacing in your stack view, you can use simpler code.
Anyway, here's my code:
class TaskletViewController: UIViewController {
#IBAction func buttonWasTapped() {
if detailContainerHideConstraint == nil {
detailContainerHideConstraint = detailContainer.heightAnchor.constraint(equalToConstant: 0)
}
let wantHidden = !(detailContainerHideConstraint?.isActive ?? false)
if wantHidden {
UIView.animate(withDuration: 0.25, animations: {
if #available(iOS 11.0, *) {
self.stackView.setCustomSpacing(0, after: self.button)
}
self.detailContainerHideConstraint?.isActive = true
self.view.window?.layoutIfNeeded()
}, completion: { _ in
if #available(iOS 11.0, *) { } else {
self.detailContainer.isHidden = true
}
})
} else {
if #available(iOS 11.0, *) { } else {
detailContainer.isHidden = false
}
UIView.animate(withDuration: 0.25, animations: {
if #available(iOS 11.0, *) {
self.stackView.setCustomSpacing(self.stackView.spacing, after: self.button)
}
self.detailContainerHideConstraint?.isActive = false
self.view.window?.layoutIfNeeded()
})
}
}
override func loadView() {
stackView.axis = .vertical
stackView.spacing = 12
stackView.translatesAutoresizingMaskIntoConstraints = false
button.translatesAutoresizingMaskIntoConstraints = false
button.backgroundColor = UIColor.green.withAlphaComponent(0.2)
button.setTitle("Tap to toggle", for: .normal)
button.addTarget(self, action: #selector(buttonWasTapped), for: .touchUpInside)
button.setContentHuggingPriority(.required, for: .vertical)
button.setContentCompressionResistancePriority(.required, for: .vertical)
stackView.addArrangedSubview(button)
detailLabel.translatesAutoresizingMaskIntoConstraints = false
detailLabel.text = "Hello, world!"
detailLabel.textAlignment = .center
detailLabel.backgroundColor = UIColor.purple.withAlphaComponent(0.2)
detailLabel.heightAnchor.constraint(equalToConstant: 80).isActive = true
detailContainer.translatesAutoresizingMaskIntoConstraints = false
detailContainer.clipsToBounds = true
detailContainer.addSubview(detailLabel)
let bottomConstraint = detailLabel.bottomAnchor.constraint(equalTo: detailContainer.bottomAnchor)
bottomConstraint.priority = .init(999)
NSLayoutConstraint.activate([
detailLabel.topAnchor.constraint(equalTo: detailContainer.topAnchor),
detailLabel.leadingAnchor.constraint(equalTo: detailContainer.leadingAnchor),
detailLabel.trailingAnchor.constraint(equalTo: detailContainer.trailingAnchor),
bottomConstraint
])
stackView.addArrangedSubview(detailContainer)
self.view = stackView
}
private let stackView = UIStackView()
private let button = UIButton(type: .roundedRect)
private let detailLabel = UILabel()
private let detailContainer = UIView()
private var detailContainerHideConstraint: NSLayoutConstraint?
}

Swift 4 upgrade issue with imageViews as bar buttons within navigation bar

So I have upgraded to swift 4 and now my left & right uiimageviews set as left/right nav button items are showing as large icons. I have figured out that the Frame setting is not being applied and I am not sure why.
Does anyone know what may cause this?
Here is some code
lazy var leftBarPic: UIImageView = {
let pic = UIImageView(frame: CGRect(x: 0, y: 0, width: 25, height: 25))
pic.clipsToBounds = true
pic.contentMode = .scaleAspectFit
pic.image = myImage.withRenderingMode(.alwaysOriginal)
pic.isUserInteractionEnabled = true
pic.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(postNewsAction)))
pic.backgroundColor = .green
return pic
}()
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.leftBarButtonItem = UIBarButtonItem(customView: leftBarPic)
}
OK I found a fix. For anyone having similar, what I did was add the property (in this instance the left navigator imageView) to the view's subview. Then added the constraints for width and height. It seems that with the upgrade setting the frame for nav items (image views only) inside the property does not work.

Custom UIButton as Navigation Item Back Button working, but does not show

let btnName = UIButton()
btnName.setImage(UIImage(named: "backIcon"), for: .normal)
btnName.addTarget(self, action: #selector(AddContactViewController.backAction), for: .touchUpInside)
let leftBarButton = UIBarButtonItem()
leftBarButton.customView = btnName
self.navigationItem.leftBarButtonItem = leftBarButton
It works fine, it does what is intended to do. However, on the navigation item it's invisible. But when I click on the area where it should be. It works.
Actually you may have two navigation bars one is of your current class and another is of your previous class.So, you can try by adding below code in your previous class.
override func viewWillDisappear(_ animated: Bool) {
self.navigationController!.navigationBar.isHidden = true
}
I also faced the same problem and it worked for me. May be it will help you.
Everything is ok, except you forgot to set the frame for your button, that's why it's not being shown.
let btnName = UIButton(frame: CGRect(x: 0, y: 0, width: 18, height: 17))
btnName.setImage(UIImage(named: "backIcon"), for: .normal)
btnName.addTarget(self, action: #selector(AddContactViewController.backAction), for: .touchUpInside)
let leftBarButton = UIBarButtonItem()
leftBarButton.customView = btnName
self.navigationItem.leftBarButtonItem = leftBarButton
Rather than hard-coding some frame values, you are better off calling the sizeToFit() method after setting the image, title, etc. I hit this problem today where a custom back button was showing OK on iOS11, but was not visible on iOS9.
btnName.sizeToFit()