为什么当我子类化 UIView 时不能在图像上绘制?

Why can't I draw on an image when I subclass UIView?

我正在尝试使用 this tutorial 中的代码在相册中的图像上绘图。从相机胶卷中选择一张照片后,imageView 被设置为照片。当用户按下绘图按钮时,tempImageView 被添加到照片上,因此用户可以在上面绘图。但是,当我尝试在图像上绘图时,什么也没有发生。为什么?

代码:

class EditViewController: UIViewController{
    var tempImageView: DrawableView!
    var imageView: UIImageView = UIImageView(image: UIImage(named: "ClearImage"))

    func draw(sender: UIButton!) {
        tempImageView = DrawableView(frame: imageView.bounds)
        tempImageView.backgroundColor = UIColor.clearColor()
        self.view.addSubview(tempImageView)
    }

}

class DrawableView: UIView {

let path=UIBezierPath()
var previousPoint:CGPoint
var lineWidth:CGFloat=10.0

// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override init(frame: CGRect) {
    previousPoint=CGPoint.zero
    super.init(frame: frame)
}

required init?(coder aDecoder: NSCoder) {
    previousPoint=CGPoint.zero
    super.init(coder: aDecoder)
    let panGestureRecognizer=UIPanGestureRecognizer(target: self, action: "pan:")
    panGestureRecognizer.maximumNumberOfTouches=1
    self.addGestureRecognizer(panGestureRecognizer)
}

override func drawRect(rect: CGRect) {
    // Drawing code
    UIColor.greenColor().setStroke()
    path.stroke()
    path.lineWidth=lineWidth
}

func pan(panGestureRecognizer:UIPanGestureRecognizer)->Void
{
    let currentPoint=panGestureRecognizer.locationInView(self)
    let midPoint=self.midPoint(previousPoint, p1: currentPoint)

    if panGestureRecognizer.state == .Began
    {
        path.moveToPoint(currentPoint)
    }
    else if panGestureRecognizer.state == .Changed
    {
        path.addQuadCurveToPoint(midPoint,controlPoint: previousPoint)
    }

    previousPoint=currentPoint
    self.setNeedsDisplay()
}

func midPoint(p0:CGPoint,p1:CGPoint)->CGPoint
{
    let x=(p0.x+p1.x)/2
    let y=(p0.y+p1.y)/2
    return CGPoint(x: x, y: y)
}

}

确保 tempImageView.userIteractionEnabled = YES。默认情况下,UIImageView 的 属性 为 NO。 在给你的 gestureRecogniser 方法设置断点后,看看它是否被调用。