Search code examples
uitableviewswiftios8uiswipegesturerecognizer

Adding UISwipeGestureRecognizer on a UIView property of a UITableViewCell custom class


I have a custom UITableViewCell class who's init method looks like this:

init(style: UITableViewCellStyle, reuseIdentifier: String!) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)

        let swipeLeft: UISwipeGestureRecognizer = UISwipeGestureRecognizer(target: self, action: "swipedLeft")
        let swipeRight: UISwipeGestureRecognizer = UISwipeGestureRecognizer(target: self, action: "swipedRight")

        swipeLeft.direction = UISwipeGestureRecognizerDirection.Left
        swipeRight.direction = UISwipeGestureRecognizerDirection.Right

        self.topLayerView?.addGestureRecognizer(swipeLeft)
        self.topLayerView?.addGestureRecognizer(swipeRight)
    }

self.topLayerViewis an IBOutlet. The problem is when I add the gestureRecognizers the self.topLayerView is nil.

if I write something like this in the init method:

if self.topLayerView? {
            println("NOT empty")
        } else {
            println("empty")
        }

it always gives me "empty". So, my question is: Where is it appropriate to put this code instead?

Any help would be much appreciated!


Solution

  • Init is too early in the life cycle of your view to expect any IBOutlets to have been set. I suggest moving your code to your cell's awakeFromNib() method, which get's called after the interface file has been fully loaded. You can find more info on this method and others in the NSObject UIKit Additions Reference.

    override func awakeFromNib() {
        super.awakeFromNib()
    
        let swipeLeft: UISwipeGestureRecognizer = UISwipeGestureRecognizer(target: self, action: "swipedLeft")
        let swipeRight: UISwipeGestureRecognizer = UISwipeGestureRecognizer(target: self, action: "swipedRight")
    
        swipeLeft.direction = UISwipeGestureRecognizerDirection.Left
        swipeRight.direction = UISwipeGestureRecognizerDirection.Right
    
        self.topLayerView?.addGestureRecognizer(swipeLeft)
        self.topLayerView?.addGestureRecognizer(swipeRight)
    }