在UITableViewCell自定义类的UIView属性上添加UISwipeGestureRecognizer

时间:2014-06-19 21:34:09

标签: uitableview swift ios8 uiswipegesturerecognizer

我有一个自定义的UITableViewCell类,它的init方法如下所示:

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.topLayerView是一个IBOutlet。问题是当我添加gestureRecognizers时self.topLayerViewnil

如果我在init方法中写出类似的内容:

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

它总是让我“空虚”。 所以,我的问题是:将代码放在哪里是恰当的?

非常感谢任何帮助!

1 个答案:

答案 0 :(得分:3)

初始化在视图的生命周期中太早,以至于期望已经设置了任何IBOutlet。我建议将代码移动到单元格的awakeFromNib()方法,该方法在接口文件完全加载后调用。您可以在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)
}