Search code examples
iosswiftclickuitapgesturerecognizer

Swift: programmatically add UITapGestureRecognizer doesn't work


I have this code block, but it does not work the way I want to. datum_view appear good, but to no avail I click on it, it does not work.

Update code:

Position

var containerView: UIView!
var tov_datum = [String]()
var datum_view: UIView!

override func viewDidLoad() {
    super.viewDidLoad()
    containerView = UIView()

    let SCREEN_SIZE = UIScreen.mainScreen().bounds


    var Y: CGFloat = 0

    for index in tov_datum {
        datum_view = UIView(frame: CGRectMake(0, Y, SCREEN_SIZE.width, 80))
        let gradientView = GradientView(frame: datum_view.bounds)
        datum_view.insertSubview(gradientView, atIndex: 0)

        let tapGestureRecognizer = UITapGestureRecognizer(target:self, action:"klikk:")
        datum_view.userInteractionEnabled = true
        datum_view.addGestureRecognizer(tapGestureRecognizer)

        containerView.addSubview(datum_view)


        Y = Y + 80
    }
    let YY = tov_datum.count * 80
    NSLayoutConstraint(item: vetítésekView, attribute: .Height, relatedBy: .Equal, toItem: nil, attribute:.NotAnAttribute, multiplier: 1.0, constant:CGFloat(YY)).active = true

    vetítésekView.addSubview(containerView)
}


func klikk(recognizer: UITapGestureRecognizer) {
    print("BOOOOYAAAA")
}

Solution

  • Doesn't look like the size of containerView is set anywhere. To quickly see if that's the problem, initialize it with the frame you're creating datum_view inside:

    let SCREEN_SIZE = UIScreen.mainScreen().bounds
    containerView = UIView(frame: SCREEN_SIZE)
    

    If that works, then figure out what size you actually want containerView to be and set up appropriate constraints.