覆盖 UIPanGestureRecognizer 的目标

Overriding target of UIPanGestureRecognizer

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

有没有一种方法可以让我的基础 class 制作基本动画并使用子 class 覆盖该方法并做一些其他事情,如下所示?

我有基地class:

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:

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)
        }
    }
}

在基础 class 中,您能否将通用功能拆分为不同的功能?这样你就不需要调用 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
        }
    }
}