Swift UIButton动作和GestureRecognizer

时间:2018-12-20 21:56:38

标签: ios swift

我正在尝试解决此问题,但我不知道该怎么做。 我有一个视图控制器,其中有一个视图(CanvasView)和三个按钮。每个按钮绘制一种形状。我希望用户单击按钮时仅在单击按钮时才在CanvasView的特定点上单击添加形状。

是否只有在单击按钮时才允许tapGesture?

这是代码:

@IBOutlet weak var CanvasView: CanvasView!

override func viewDidLoad() {
    super.viewDidLoad()

    let tapGR = UITapGestureRecognizer(target: self, action: #selector(tap(_:)))
    tapGR.numberOfTapsRequired = 2
    CanvasView.isUserInteractionEnabled = true
    CanvasView.addGestureRecognizer(tapGR)
}

@IBAction func tap(_ sender: UITapGestureRecognizer) {
    let tapPoint = sender.location(in: CanvasView)
    let shapeView = ShapeSquare(origin: tapPoint)
    CanvasView.addSubview(shapeView)
}

@IBAction func DrawSquare(_ sender: UIButton) {
    CanvasView.setNeedsDisplay()
}

1 个答案:

答案 0 :(得分:0)

保持禁用手势,直到轻击按钮。

首先将手势设为属性:

var tapGR: UITapGestureRecognizer!

然后更新viewDidLoad

tapGR = UITapGestureRecognizer(target: self, action: #selector(tap(_:)))
tapGR.isEnabled = false

然后在您的按钮处理程序中:

tapGR.isEnabled = true