Swift: 如何在子类的init方法中对指令进行排序

Swift: how to order instructions in init method of a subclass

我需要实现这个 class:

class PinImageView: UIImageView {

    var lastLocation:CGPoint
    var panRecognizer:UIPanGestureRecognizer

    init(imageIcon: UIImage?, location:CGPoint) {
        self.lastLocation = location
        super.init(image: imageIcon)
        self.center = location
        self.panRecognizer = UIPanGestureRecognizer(target:self,  action:"detectPan:")
        self.gestureRecognizers = [panRecognizer]
    }
}

我认为存在一种 "cyclic" 问题,因为编译器希望我在调用 super.init(image: imageIcon) 之前初始化 panRecognizerpanRecognizer 具有 self 作为目标,我们只能在调用 super init 方法后使用 self

我该如何解决这个问题?

这是一个非可选的实例变量

var panRecognizer:UIPanGestureRecognizer

因此您必须在完成 init 之前为其设置一个值,具体如您所见,在调用 super.

之前

不一定非得这样。相反,它可以是一个延迟加载的实例变量,因此它会在您第一次请求时创建。

现在,当您 init 时,您可以设置实例、调用 super,然后添加手势识别器(这将在此过程中创建手势)。

lazy var panRecognizer : UIPanGestureRecognizer = {
    return UIPanGestureRecognizer(target:self, action:"detectPan:")
}()