Reputation: 219
I just started this but I'm having some trouble. Xcode finds the method and accepts it as a selector. But whenever I tap the view nothing happens (I'm creating views via code. They appear fine on the simulator, but the gesture recognizer I added to the view doesn't work).
Inside viewDidLoad in the view controller:
let tile = BoardTile(x: 0, y: 100, size: 50)
view.addSubview(tile.view)
The stuff I'm trying to do
import UIKit
class BoardTile: NSObject{
let view: UIView
let label: UILabel
init(x:Int, y:Int, size:Int){
view = UIView(frame: CGRect(x: x, y: y, width: size, height: size))
view.backgroundColor = ViewController.baseColor
label = UILabel(frame: CGRect(x: 0, y: 0, width: size, height: size))
label.text = "1"
label.font = font
label.textAlignment = .Center
view.addSubview(label)
//***********HELP HERE, DOESN'T WORK***********//
let tap = UITapGestureRecognizer()
self.view.addGestureRecognizer(tap)
tap.addTarget(self, action: #selector(tapped))
}
func tapped(){
// Never prints when I tap:
print("tapped!")
}
}
Upvotes: 0
Views: 66
Reputation: 7466
What keeps the "tile" object alive? If the "tile" instance dies within the method scope, the view and the label dies with it.
Upvotes: 1