Kawin P.
Kawin P.

Reputation: 188

Swift - Adding touch to UIImageView

I'm following a tutorial online and I'm trying to add touch detection to an UIImageView. I realize that this can be done with a gesture recognizer but I have a different problem and I don't know how to ask for it.

Basically, I added an overlay UIButton initialized from the frame of imageView. However, I have to move the frame down 64 px because of the navigation bar. My imageView is added form the storyboard but UIButton is added programmatically.

Is there a way to do this without adding 64 px manually? This is no biggies but since the frame of the imageView when printing is (10, 10, 355, 450) and the frame of UIButton is (10, 74, 355, 450), it kinda ticks me off a little bit.

Let me clarify, I'm wondering why view controller doesn't take into account the size of the navigation bar when adding subview programmatically? It seems to handle this just fine when adding subview from Storyboard.

Without adding 64px:

    overlay = UIButton(frame: imageView.frame)
    overlay.backgroundColor = UIColor.red
    overlay.addTarget(self, action: #selector(imageViewTapped), for: .touchUpInside)
    view.addSubview(overlay)

With 64px added - fits perfectly

    overlay = UIButton(frame: imageView.frame.offsetBy(dx: 0, dy: 64))
    overlay.backgroundColor = UIColor.red
    overlay.addTarget(self, action: #selector(imageViewTapped), for: .touchUpInside)
    view.addSubview(overlay)

Upvotes: 1

Views: 2230

Answers (3)

Jayeshkumar Sojitra
Jayeshkumar Sojitra

Reputation: 2511

You can use UITapGestureRecognizer for the same as given below.

    let bg = UIImageView(image: UIImage(named: "Home"))
    bg.frame = self.view.frame
    self.view.addSubview(bg)

    let tapRecognizer = UITapGestureRecognizer(target: self, action: #selector(SecondViewController.onTapScreen))
    bg.isUserInteractionEnabled = true
    bg.addGestureRecognizer(tapRecognizer)

Handle tap event as given below

    func onTapScreen() {
         // Handle touch here.
    }

By this way you don't need to use button also so it can avoid multiple controls.

Upvotes: 2

Sandeep Kumar
Sandeep Kumar

Reputation: 328

You can add button on image view.

Try This :

let overlay = UIButton(frame: imageView.bounds)
        imageView.isUserInteractionEnabled = true
        overlay.backgroundColor = UIColor.red.withAlphaComponent(0.3)
        overlay.addTarget(self, action: #selector(imageViewTapped), for: .touchUpInside)
        imageView.addSubview(overlay)

Upvotes: 2

Usman Javed
Usman Javed

Reputation: 2455

Set your UIViewController's navigationbar to Opaque Navigation Bar. It will start you view below navigation bar.

enter image description here

Upvotes: 0

Related Questions