Vijesh Kk Vijesh Kk - 3 months ago 13
Swift Question

Swift - Getting tap location on a button which was created through custom UIView class

I have a main scrollerview in my main

UIViewController
and a custom
UIView
class. This custom
UIView
class has few lines of code to create
Button
and
Label
programmatically. The action to be performed by
Button
click is working fine, but I also need to get the exact tap location (
CGPoint
) on the button as the button is long and tap x-coordinate is required for next actions. I tried few solutions got from stackoverflow and is working for other objects like
Label
and
Imageview
but doesn't work for button.

My custom UIView class:

import UIKit
class DrawProj: UIView {

override func drawRect(rect: CGRect) {
let button = UIButton(type: .System)
button.frame = CGRectMake(24, 15, linewidth - 25, 20)
button.backgroundColor = UIColor.orangeColor()
button.addTarget(nil, action: "onButtonTap:", forControlEvents: .TouchUpInside)
self.addSubview(button)
}
}


And Code in main Viewcontroller

let DrawProjectLanes = DrawProj(frame: CGRect(x: startx, y: starty, width: endx , height: 50))
DrawProjectLanes.backgroundColor = UIColor.clearColor()
DrawProjectLanes.userInteractionEnabled = true
MainScroller.addSubview(DrawProjectLanes)

Answer

You should override touchesBegan for this to work:

override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {

}

Then declare your button subview as a property:

class DrawProj: UIView {
    var button: UIButton!

    override func drawRect(rect: CGRect) {
        button = UIButton(type: .System) 
        button.frame = CGRectMake(24, 15, linewidth - 25, 20)
        button.backgroundColor = UIColor.orangeColor()
        button.addTarget(nil, action: "onButtonTap:", forControlEvents: .TouchUpInside)
        self.addSubview(button)
    }
}

In touchesBegan, do this to get the x position of the tap, relative to the button's frame:

let posX = touches.first!.locationInView(button).x

Then, you can use this posX variable however you want.

How to instantiate a view controller:

In the storyboard, select the VC that you would like to present. Go to the identity inspector, set a Storyboard ID for the VC:

enter image description here

Then in code,

let sb = UIStoryboard(name: "Main", bundle: nil)
let viewController = sb.instantiateViewControllerWithIdentifier("put the storyboard ID that you set earlier here")
let topViewController = UIApplication.sharedApplication().keyWindow?.rootViewController?.presentationController
topViewController?.presentViewController(viewController, animated: true, completion: nil)