Swift UITapGesture on view in a titleView not working - ios

I have a UINavigationItem and I set it's titleView to a UIView which has a UILabel and UIImageView embedded. I'm attempting to add a UITapGestureRecognizer to the view but it doesn't seem to work. Any solutions? Also, adding a gestureRecognizer to the whole navigationBar isn't an option as I have a rightBarButtonItem and want to make use of the back button.
Here is my code:
func configureTitleView() {
guard let profile = profile else {
// Pop navController
return
}
let titleView = UIView()
titleView.frame = CGRect(x: 0, y: 0, width: 100, height: 40)
let containerView = UIView()
containerView.translatesAutoresizingMaskIntoConstraints = false
titleView.addSubview(containerView)
let profileImageView = UIImageView()
profileImageView.translatesAutoresizingMaskIntoConstraints = false
profileImageView.contentMode = .scaleAspectFill
profileImageView.clipsToBounds = true
let imageURL = URL(string: profile!.firstProfilePicture!)
profileImageView.sd_setImage(with: imageURL)
containerView.addSubview(profileImageView)
profileImageView.leftAnchor.constraint(equalTo: containerView.leftAnchor).isActive = true
profileImageView.centerYAnchor.constraint(equalTo: containerView.centerYAnchor).isActive = true
profileImageView.widthAnchor.constraint(equalToConstant: 36).isActive = true
profileImageView.heightAnchor.constraint(equalToConstant: 36).isActive = true
profileImageView.layer.cornerRadius = 36 / 2
let nameLabel = UILabel()
containerView.addSubview(nameLabel)
nameLabel.text = profile!.displayName!
nameLabel.textColor = .white
nameLabel.translatesAutoresizingMaskIntoConstraints = false
nameLabel.leftAnchor.constraint(equalTo: profileImageView.rightAnchor, constant: 8).isActive = true
nameLabel.centerYAnchor.constraint(equalTo: profileImageView.centerYAnchor).isActive = true
nameLabel.rightAnchor.constraint(equalTo: containerView.rightAnchor).isActive = true
nameLabel.heightAnchor.constraint(equalTo: profileImageView.heightAnchor).isActive = true
containerView.centerXAnchor.constraint(equalTo: titleView.centerXAnchor).isActive = true
containerView.centerYAnchor.constraint(equalTo: titleView.centerYAnchor).isActive = true
self.navigationItem.titleView = titleView
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(self.openProfile))
tapGesture.numberOfTapsRequired = 1
titleView.addGestureRecognizer(tapGesture)
titleView.isUserInteractionEnabled = true
}

Beginning with iOS 11, views added to toolbars as UIBarButtonItem using UIBarButtonItem(customView:) are now laid out using auto layout. This includes title views added to a UINavigationBar through the navigationItem.titleView property of a UIViewController. You should add sizing constraints on your titleView. For example:
titleView.widthAnchor.constraint(equalToConstant: 100).isActive = true
titleView.heightAnchor.constraint(equalToConstant: 40.0).isActive = true
Otherwise, auto layout will use the intrinsic content size of your title view which is CGSize.zero. Gestures are masked to the bounds of the view they are attached to even if the sub views of that view are not. Because the bounds of titleView without constraints is CGRect.zero it will never fire. Add constraints and it works as expected.
For more information see the WWDC 2017 session Updating your app for iOS 11.

You do not need to add explicit height and width constant constraint to custom view.
Just add subviews to custom view, add width and height anchor.
let customView = UIView()
let button = UIButton(type: .custom)
button.translatesAutoresizingMaskIntoConstraints = false
customView.addSubview(button)
[
button.widthAnchor.constraint(equalTo: customView.widthAnchor),
button.heightAnchor.constraint(equalTo: customView.heightAnchor),
].forEach({$0.isActive = true})
navigationItem.titleView = customView

Related

TapGestureRecognizer not working in UIView subviews

I want to add a tap gesture recognizer to a custom UIView (which represent an Image and a Label). It seems that the gesture recognizer is not added to the view or that the subviews are not considered as the UIView itself, hence not working.
Here is how I add my view :
Navbar.swift :
let indexSubview = IconTextView(svgName: "https://placeholder.pics/svg/30", textKey: "Index")
self.indexButton.addSubview(indexSubview)
let indexButtonTap = UITapGestureRecognizer(target: self, action: #selector(goToIndex))
indexButton.addGestureRecognizer(indexButtonTap)
(IconTextView being my custom view)
Then when I tap the indexButtonnothing is working.
My tap function, just in case:
#objc func goToIndex(sender:UITapGestureRecognizer) {
print("GO TO INDEX")
router.setRoute(routeName: "INDEX", routeParam: "")
}
I don't understand why it is not working, the userInteractions are enabled on all the elements.
Your precedent code + tap gesture, I edit constraints, add containerView:
class Aiutotipo: UIViewController {
let myImageView: UIImageView = {
let iv = UIImageView()
iv.contentMode = .scaleToFill
iv.clipsToBounds = true
iv.backgroundColor = .red
iv.translatesAutoresizingMaskIntoConstraints = false
return iv
}()
let myLabel: UILabel = {
let label = UILabel()
label.text = "Débats"
label.textColor = .white
label.textAlignment = .center
label.font = .systemFont(ofSize: 30, weight: .semibold)
label.translatesAutoresizingMaskIntoConstraints = false
return label
}()
let containerView = UIView() //your container view
override func viewDidLoad() {
super.viewDidLoad()
containerView.backgroundColor = .red // red bacground for container view visible, set .clear for transparent bg
containerView.isUserInteractionEnabled = true
containerView.translatesAutoresizingMaskIntoConstraints = false
let indexButtonTap = UITapGestureRecognizer(target: self, action: #selector(goToIndex))
containerView.addGestureRecognizer(indexButtonTap)
myImageView.image = UIImage(named: "profilo") // set here your image
let myWidth = myLabel.intrinsicContentSize.width // This reveal only text width in label
view.addSubview(containerView)
containerView.heightAnchor.constraint(equalToConstant: myWidth + 50).isActive = true
containerView.widthAnchor.constraint(equalToConstant: myWidth).isActive = true
containerView.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
containerView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
containerView.addSubview(myImageView)
myImageView.topAnchor.constraint(equalTo: containerView.topAnchor).isActive = true
myImageView.leadingAnchor.constraint(equalTo: containerView.leadingAnchor).isActive = true
myImageView.trailingAnchor.constraint(equalTo: containerView.trailingAnchor).isActive = true
myImageView.heightAnchor.constraint(equalTo: myImageView.widthAnchor).isActive = true
containerView.addSubview(myLabel)
myLabel.topAnchor.constraint(equalTo: myImageView.bottomAnchor).isActive = true
myLabel.leadingAnchor.constraint(equalTo: containerView.leadingAnchor).isActive = true
myLabel.trailingAnchor.constraint(equalTo: containerView.trailingAnchor).isActive = true
myLabel.bottomAnchor.constraint(equalTo: containerView.bottomAnchor).isActive = true
}
#objc fileprivate func goToIndex() {
print("GO TO INDEX")
}
}
This is the result

How do I add a UIView to a UIScrollView In Swift programmatically?

I am trying to add a view to a UIScrollView just using code, but the view doesn't appear in the UIScrollView and I'm not sure why. When I added a button or label, they show up.
import UIKit
class profileViewController: UIViewController, UIScrollViewDelegate {
var label : UILabel = {
let label = UILabel()
label.text = "Profile"
label.textColor = UIColor.init(white: 0.80, alpha: 1)
label.font = UIFont.systemFont(ofSize: 40)
label.translatesAutoresizingMaskIntoConstraints = false
return label
}()
var scrollview : UIScrollView = {
let scrollview = UIScrollView()
scrollview.translatesAutoresizingMaskIntoConstraints = false
scrollview.backgroundColor = .clear
return scrollview
}()
var greyview : UIView = {
let view = UIView()
view.translatesAutoresizingMaskIntoConstraints = false
view.backgroundColor = UIColor.init(white: 0.70, alpha: 1)
view.backgroundColor = UIColor.gray
return view
}()
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .white
view.addSubview(label)
label.centerYAnchor.constraint(equalTo: view.safeAreaLayoutGuide.centerYAnchor).isActive = true
label.centerXAnchor.constraint(equalTo: view.safeAreaLayoutGuide.centerXAnchor).isActive = true
scrollview.delegate = self
view.addSubview(scrollview)
scrollview.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor).isActive = true
scrollview.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
scrollview.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true
scrollview.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true
scrollview.contentSize = CGSize.init(width: view.frame.size.width, height: view.frame.size.height + 500)
scrollview.addSubview(greyview)
greyview.topAnchor.constraint(equalTo: scrollview.topAnchor).isActive = true
greyview.trailingAnchor.constraint(equalTo: scrollview.trailingAnchor).isActive = true
greyview.leadingAnchor.constraint(equalTo: scrollview.leadingAnchor).isActive = true
greyview.heightAnchor.constraint(equalToConstant: 100).isActive = true
}
}
this is one way:
self.scrollView = UIScrollView.init()
if let scrollView = self.scrollView {
scrollView.showsVerticalScrollIndicator = true
self.view.add(scrollView)
scrollView.translatesAutoresizingMaskIntoConstraints = false
self.addConstraint(UtilConstraint.addTopConstraint(from: scrollView, to: self, value: 0))
self.addConstraint(UtilConstraint.addBottomConstraint(from: scrollView, to: self, value: 0))
self.addConstraint(UtilConstraint.addLeftLeftConstraint(from: scrollView, to: self, value: 0))
self.addConstraint(UtilConstraint.addRightRightConstraint(from: scrollView, to: self, value: 0))
NSLayoutConstraint.activate(self.constraints)
greyview.translatesAutoresizingMaskIntoConstraints = false
scrollView.addSubview(greyview)
greyview.topAnchor.constraint(equalTo: scrollView.topAnchor).isActive = true
greyview.leftAnchor.constraint(equalTo: scrollView.leftAnchor).isActive = true
greyview.bottomAnchor.constraint(equalTo: scrollView.bottomAnchor).isActive = true
greyview.widthAnchor.constraint(equalTo: scrollView.widthAnchor).isActive = true
}
Remember, your greyview should have hight defined either statically or via. components inside.
though , what you were missing was defining a width. I have done it using widthAnchor. (assuming you need a vertical scroll)
This is probably because your greyview doesnt have its bottomAnchor. It needs the top and bottom anchors in order to work properly inside the scrollView:
scrollview.addSubview(greyview)
greyview.topAnchor.constraint(equalTo: scrollview.topAnchor).isActive = true
greyview.centerXAnchor.constraint(equalTo: scrollview.centerXAnchor).isActive = true
greyview.heightAnchor.constraint(equalToConstant: 100).isActive = true
greyview.widthAnchor.constraint(equalToConstant: 100).isActive = true
Add a widthAnchor, here I centered it in the scroll view but it is up to you to place it how you want it. Also if you add more items just make sure the bottom-most item has a bottomAnchor attached to the scrollView bottomAnchor or it will not scroll.
Update:
I don't know how you want your greyview to look, but if you make the height taller than the contentSize of the scrollView it will scroll, and make sure you have the bottomAnchor:
scrollview.contentSize = CGSize.init(width: view.frame.size.width, height: view.frame.size.height)
scrollview.addSubview(greyview)
greyview.topAnchor.constraint(equalTo: scrollview.topAnchor).isActive = true
greyview.bottomAnchor.constraint(equalTo: scrollview.bottomAnchor).isActive = true
greyview.heightAnchor.constraint(equalTo: scrollview.heightAnchor, constant: 500).isActive = true
greyview.widthAnchor.constraint(equalTo: scrollview.widthAnchor).isActive = true
This makes the greyview width equal to scrollview width, and height equal to scrollview height + 500 so that it scrolls.

UIPickerView placement on top of view

I am trying to place a UIPickerView on top of my TableView when a button is clicked. I tried using the storyboard, but it moves the rows of the table down. What I want is the picker to appear as a popover when the button is clicked, then disappear when an option is selected.
Here is the code I am using to get the picker to display:
let picker = UIPickerView()
let container = UILayoutGuide()
view.addLayoutGuide(container)
picker.backgroundColor = UIColor.white
picker.dataSource = self
picker.delegate = self
view.addSubview(picker)
picker.leadingAnchor.constraint(equalTo: container.leadingAnchor).isActive = true
picker.trailingAnchor.constraint(equalTo: container.trailingAnchor).isActive = true
picker.topAnchor.constraint(equalTo: container.topAnchor).isActive = true
picker.heightAnchor.constraint(equalToConstant: 100).isActive = true
picker.setContentHuggingPriority(UILayoutPriority.required, for: .horizontal)
However, the picker shows up like this:
I don't understand why the picker view is not stretched until the end because I am setting the trailingAnchor as the parent view's trailingAnchor.
Have you set translatesAutoresizingMaskIntoConstraints of your picker view to false? It ignores constraints unless you do that
If trailing anchor is not working, then try setting left, top and right to 0 and provide a height as well (if you don't wish to cover the complete tableView) .
Also, add your pickerView on top of your tableView for these
constraints to be applied
If you wish to do it programatically, you can provide the constraints while you're creating the UIPickerView object
let pickerView = UIPickerView(frame: CGRect(x: 0, y: 0, width: tableView.frame.width, height: 50))
Instead of the layout guide, you can directly use your table view as of your relative view.
Coding Example:
func addPickerView() {
let picker = UIPickerView()
// let container = UILayoutGuide()
// view.addLayoutGuide(container)
picker.translatesAutoresizingMaskIntoConstraints = false
picker.backgroundColor = UIColor.red
picker.dataSource = self
picker.delegate = self
view.addSubview(picker)
picker.leadingAnchor.constraint(equalTo: self.view.leadingAnchor).isActive = true
picker.trailingAnchor.constraint(equalTo: self.view.trailingAnchor).isActive = true
picker.topAnchor.constraint(equalTo: self.view.topAnchor).isActive = true
picker.heightAnchor.constraint(equalToConstant: 100).isActive = true
picker.setContentHuggingPriority(UILayoutPriority.required, for: .horizontal)
}
Above code produces the following output which is stretched to its parent view.
Set constraints equal to parent view then show perfect.
let topBarHeight = UIApplication.shared.statusBarFrame.size.height +
(self.navigationController?.navigationBar.frame.height ?? 0.0)
let picker = UIPickerView()
picker.translatesAutoresizingMaskIntoConstraints = false
let container = UILayoutGuide()
view.addLayoutGuide(container)
picker.backgroundColor = UIColor.lightGray
picker.dataSource = self
picker.delegate = self
view.addSubview(picker)
picker.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true
picker.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true
picker.topAnchor.constraint(equalTo: view.topAnchor, constant: topBarHeight).isActive = true
picker.heightAnchor.constraint(equalToConstant: 200).isActive = true
picker.setContentHuggingPriority(UILayoutPriority.required, for: .horizontal)
I figured out the best way to do it, in the Interface Builder itself. I had to change the TableViewController to a ViewController and put the TableView inside of it (setting the ViewController as a TableViewDelegate and TableViewDataSource). This allowed me to place the PickerView on the IB, as a layered view on top of my table cells. Then I could hide and show it as I pleased by creating an IBOutlet for it and setting the .isHidden property appropriately.
More info here: Swift: TableView in ViewController

How to make auto-layout constraint dependent on multiple other anchors?

How can auto-layout be used to make a view's height equal to the sum of two other view's heights?
For example:
viewA.heightAnchor.constraint(equalTo: ...),
viewB.heightAnchor.constraint(equalTo: ...),
viewC.heightAnchor.constraint(equalTo: viewA.heightAnchor + viewB.heightAnchor)
Is there a solution that does not involve setting a constant value and recalculating it on every view bounds change?
You can, but only with the help of some helper views, I think. See this example playground I just now cooked up that achieves this:
import Foundation
import UIKit
import PlaygroundSupport
let vc = UIViewController()
vc.view = UIView()
vc.view.backgroundColor = .white
let viewA = UIView()
let viewB = UIView()
let viewC = UIView()
viewA.backgroundColor = .red
viewB.backgroundColor = .green
viewC.backgroundColor = .blue
viewA.translatesAutoresizingMaskIntoConstraints = false
viewB.translatesAutoresizingMaskIntoConstraints = false
viewC.translatesAutoresizingMaskIntoConstraints = false
vc.view.addSubview(viewA)
vc.view.addSubview(viewB)
vc.view.addSubview(viewC)
let helperViewA = UIView()
let helperViewB = UIView()
helperViewA.translatesAutoresizingMaskIntoConstraints = false
helperViewB.translatesAutoresizingMaskIntoConstraints = false
helperViewA.isHidden = true
helperViewB.isHidden = true
vc.view.addSubview(helperViewA)
vc.view.addSubview(helperViewB)
viewA.bottomAnchor.constraint(equalTo: vc.view.bottomAnchor).isActive = true
viewA.leadingAnchor.constraint(equalTo: vc.view.leadingAnchor).isActive = true
viewA.trailingAnchor.constraint(equalTo: viewB.leadingAnchor).isActive = true
viewA.heightAnchor.constraint(equalToConstant: 20.0).isActive = true
viewB.bottomAnchor.constraint(equalTo: vc.view.bottomAnchor).isActive = true
viewB.widthAnchor.constraint(equalTo: viewA.widthAnchor, multiplier: 1.0).isActive = true
viewB.trailingAnchor.constraint(equalTo: vc.view.trailingAnchor).isActive = true
viewB.heightAnchor.constraint(equalToConstant: 40.0).isActive = true
viewA.heightAnchor.constraint(equalTo: helperViewA.heightAnchor, multiplier: 1.0).isActive = true
viewB.heightAnchor.constraint(equalTo: helperViewB.heightAnchor, multiplier: 1.0).isActive = true
helperViewA.bottomAnchor.constraint(equalTo: helperViewB.topAnchor).isActive = true
viewC.widthAnchor.constraint(equalToConstant: 100).isActive = true
viewC.topAnchor.constraint(equalTo: helperViewA.topAnchor).isActive = true
viewC.bottomAnchor.constraint(equalTo: helperViewB.bottomAnchor).isActive = true
helperViewA.leadingAnchor.constraint(equalTo: viewC.leadingAnchor).isActive = true
helperViewA.trailingAnchor.constraint(equalTo: viewC.trailingAnchor).isActive = true
helperViewB.leadingAnchor.constraint(equalTo: viewC.leadingAnchor).isActive = true
helperViewB.trailingAnchor.constraint(equalTo: viewC.trailingAnchor).isActive = true
viewC.centerXAnchor.constraint(equalTo: vc.view.centerXAnchor).isActive = true
viewC.centerYAnchor.constraint(equalTo: vc.view.centerYAnchor).isActive = true
vc.view.frame.size = CGSize(width: 375, height: 667)
PlaygroundPage.current.liveView = vc.view
The idea is that you have two helper views stacked vertically on each other, connected by the top one's bottomAnchor and the bottom one's topAnchor. You then set each of these helper views' heights to be equal to your viewA and viewB heights. Then, your viewC can be attached to the top view's topAnchor and the bottom view's bottomAnchor, which gives the result of viewC being the height of viewA's height plus viewB's height.

UINavigationBar contentMode not being set

I am trying to make the background of the UINavigationBar an image, and the image isn't the exact size of the bar. I can't seem to set the contentMode of the bar correctly for some reason. This is the code I have:
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
// ...
let image = UIImage(named: object?.imageName ?? "")
navigationController?.navigationBar.alpha = 0
navigationController?.navigationBar.setBackgroundImage(image, for: .default)
self.navigationController?.navigationBar.contentMode = .scaleAspectFill
UIView.animate(withDuration: Double(UINavigationControllerHideShowBarDuration), animations: {
self.navigationController?.navigationBar.alpha = 1
})
}
I don't know what I'm doing wrong, or maybe contentMode just doesn't do anything for UINavigationBar.
What's currently happening is the background image is just presented again like mosaic
Thanks
You can create UIView and add Image and Text to it, but you must set constraints
let titleView = UIView()
titleView.frame = CGRect(x: 0, y: 0, width: 100, height: 40)
let containerView = UIView()
containerView.translatesAutoresizingMaskIntoConstraints = false
titleView.addSubview(containerView)
let profileImageView = UIImageView()
profileImageView.translatesAutoresizingMaskIntoConstraints = false
profileImageView.contentMode = .scaleAspectFill
profileImageView.layer.cornerRadius = 20
profileImageView.clipsToBounds = true
containerView.addSubview(profileImageView)
profileImageView.leftAnchor.constraint(equalTo: containerView.leftAnchor).isActive = true
profileImageView.centerYAnchor.constraint(equalTo: containerView.centerYAnchor).isActive = true
profileImageView.widthAnchor.constraint(equalToConstant: 40).isActive = true
profileImageView.heightAnchor.constraint(equalToConstant: 40).isActive = true
self.navigationItem.titleView = titleView
titleView.addGestureRecognizer(UITapGestureRecognizer(target:
self, action: #selector(func)))
I hope that I helped you

Resources