覆盖UIPanGestureRecognizer

时间:2016-12-24 03:45:39

标签: swift override subclass uipangesturerecognizer

我有一个基类来处理单元格的一些基本动画。在我的子类中,我已经覆盖了识别器目标并想要做其他一些事情,但是翻译总是0因为我在基类中调用了翻译被重置为.zero

有没有办法让我的基类来做基本的动画,并使用子类来覆盖方法,并做一些其他的东西,如下所示?

我有一个基类:

class Base: UITableViewCell {

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

        let gesture = UIPanGestureRecognizer(target: self, action: #selector(handlePan))
        addGestureRecognizer(gesture)
    }

    func handlePan(recognizer: UIPanGestureRecognizer) {
        if recognizer.state == .changed {
            let translation = recognizer.translation(in: self)

            ...

            recognizer.setTranslation(.zero, in: self)
        }
    }
}

我的子类:

class Sub: Base {

    override func handlePan(recognizer: UIPanGestureRecognizer) {
        super.handlePan(recognizer: recognizer)

        if recognizer.state == .changed {
            let translation = recognizer.translation(in: self)

            print(translation.x) // is always 0

            recognizer.setTranslation(.zero, in: self)
        }
    }
}

1 个答案:

答案 0 :(得分:0)

在基类中,您可以将常用功能拆分为不同的功能吗?这样你就不需要调用super.handlePan:

class Base: UITableViewCell {
    override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        let gesture = UIPanGestureRecognizer(target: self, action: #selector(handlePan))
        addGestureRecognizer(gesture)
    }

    func handlePan(recognizer: UIPanGestureRecognizer) {
        if recognizer.state == .changed {
            let translation = recognizer.translation(in: self)
            performBaseAnimation(recognizer)
            recognizer.setTranslation(.zero, in: self)
        }
    }
    func performBaseAnimation(_ recognizer: UIPanGestureRecognizer) {
        // perform common actions here
    }
}
class Sub: Base {
    override func handlePan(recognizer: UIPanGestureRecognizer) {
        super.handleBaseAnimation(recognizer)
        if recognizer.state == .changed {
            // perform subclass actions here
        }
    }
}