如何从Swift中的valueChanged事件中获取触摸坐标

Sur*_*gch 10 ios uicontrolevents swift

背景

我之前已经学会了如何使用手势识别器或continueTrackingWithTouch获得当前触摸位置的连续更新,然后使用它们执行以下操作:

在此输入图像描述

但是,现在,我想学习如何使用目标做同样的事情.我已经可以得到触摸下来,并通过使用触摸起来的事件TouchDownTouchUpInside,但我不知道如何获得持续的更新.我以为它会使用这个ValueChanged事件,但到目前为止还没有用.

这是我尝试过的:

ViewController.swift

import UIKit
class ViewController: UIViewController {

    @IBOutlet weak var myCustomControl: MyCustomControl!
    @IBOutlet weak var trackingBeganLabel: UILabel!
    @IBOutlet weak var trackingEndedLabel: UILabel!
    @IBOutlet weak var xLabel: UILabel!
    @IBOutlet weak var yLabel: UILabel!

    override func viewDidLoad() {
        super.viewDidLoad()

        // these work
        myCustomControl.addTarget(self, action: "myTouchDown", forControlEvents: UIControlEvents.TouchDown)
        myCustomControl.addTarget(self, action: "myTouchUpInside", forControlEvents: UIControlEvents.TouchUpInside)

        // this doesn't work
        myCustomControl.addTarget(self, action: "myValueChangedEvent:",
            forControlEvents: UIControlEvents.ValueChanged)
    }

    // this works
    func myTouchDown() {
        trackingBeganLabel.text = "Touched down"
    }

    // this works
    func myTouchUpInside() {
        trackingEndedLabel.text = "Touch up inside"
    }

    // this doesn't work, function never gets called
    func myValueChangedEvent(sender: UIControl) { 
        let location = sender.convertPoint(CGPointZero, toView: myCustomControl) 
        xLabel.text = "x: \(location.x)"
        yLabel.text = "y: \(location.y)"
    }
}
Run Code Online (Sandbox Code Playgroud)

MyCustomControl.swift

import UIKit
class MyCustomControl: UIControl {
    // currently empty. Do I need to add something here?
}
Run Code Online (Sandbox Code Playgroud)

笔记

  • 获得@ CaseyWagner的回答后更改了代码.编译器不再抛出错误但UIControlEvents.ValueChanged永远不会被触发.
  • 这个问题是我试图找到答案的方法1:添加目标部分的完整答案.

Kon*_*zov 10

使用UIControlEvents.TouchDragInside而不是UIControlEvents.ValueChanged(还注意到action方法接收两个参数):

myCustomControl.addTarget(self, action: "didDragInsideControl:withEvent:",
        forControlEvents: UIControlEvents.TouchDragInside)
Run Code Online (Sandbox Code Playgroud)

处理函数如下所示:

func didDragInsideControl(control: MyCustomControl, withEvent event: UIEvent) {
    let touch = event.touchesForView(control)!.first!
    let location = touch.locationInView(control)
    xLabel.text = "x: \(location.x)"
    yLabel.text = "y: \(location.y)"
}
Run Code Online (Sandbox Code Playgroud)