我有一个视图控制器,我试图通过单击按钮在主视图上动态创建一个CanvasView自定义类。
我可以创建CanvasView实例并在视图上看到它,但是CanvasView类中的函数根本不会为运行时生成的实例触发。
在视图上有一个名为canvasView1的设计时创建的视图,它的一切工作正常。
我是IOS新手,所以我可能犯了个愚蠢的错误。
有什么想法吗?
提前谢谢你的帮助。

class ViewController: UIViewController {


    @IBOutlet weak var click: UIButton!


    @IBAction func clicked(_ sender: Any) {
    enter code here
        var  imageView1 : CanvasView!
        imageView1 = CanvasView(frame:CGRect(x: 330, y: 330, width: 100, height: 200));
        imageView1.backgroundColor = UIColor.blue
        self.view.addSubview(imageView1)
    }
    @IBOutlet weak var canvasView1: CanvasView!

这是我的CanvasView类,它派生自UIImageView
import UIKit

let π = Double.pi

        class CanvasView: UIImageView {


            // Parameters
          private let defaultLineWidth:CGFloat = 3

          private var drawColor: UIColor = UIColor.red


            override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
                guard let touch = touches.first else { return }

                UIGraphicsBeginImageContextWithOptions(bounds.size, false, 0.0)
                let context = UIGraphicsGetCurrentContext()

                // Draw previous image into context
                image?.draw(in: bounds)

                drawStroke(context: context, touch: touch)

                // Update image
                image = UIGraphicsGetImageFromCurrentImageContext()
                UIGraphicsEndImageContext()
            }
     private func drawStroke(context: CGContext?, touch: UITouch) {
        let previousLocation = touch.previousLocation(in: self)
        let location = touch.location(in: self)

        // Calculate line width for drawing stroke
        let lineWidth = lineWidthForDrawing(context: context, touch: touch)

        // Set color
        drawColor.setStroke()

        // Configure line
        context!.setLineWidth(lineWidth)
        context!.setLineCap(.round)


        // Set up the points
        context?.move(to: CGPoint(x:previousLocation.x, y:previousLocation.y))
        context?.addLine(to: CGPoint(x:location.x, y:location.y))
        // Draw the stroke
        context!.strokePath()

      }

      private func lineWidthForDrawing(context: CGContext?, touch: UITouch) -> CGFloat {

        let lineWidth = defaultLineWidth

        return lineWidth
      }

        func clearCanvas(animated: Bool) {
        if animated {
            UIView.animate(withDuration: 0.5, animations: {
            self.alpha = 0
            }, completion: { finished in
              self.alpha = 1
              self.image = nil
          })
        } else {
          image = nil
        }
      }
    }

最佳答案

如评论中所述:

  imageView1.isUserInteractionEnabled = true

解决了这个问题。
谢谢。

关于ios - 从UIImageView派生的动态创建控件缺少功能,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/48192452/

10-11 08:58