我已經previously learned如何使用手勢識別或continueTrackingWithTouch
來獲取當前觸摸位置的不斷更新和再使用那些做是這樣的:
但是現在,我想學習如何使用目標,以做同樣的事情。我已經可以通過使用TouchDown
和TouchUpInside
來觸摸並修改事件,但我不知道如何獲得持續更新。我認爲它將使用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)"
}
}
MyCustomControl.swift
import UIKit
class MyCustomControl: UIControl {
// currently empty. Do I need to add something here?
}
注意
- 獲得@ CaseyWagner的答案後更改了代碼。編譯器不會再拋出錯誤,但不會被解僱。
- 這個問題是我試圖對方法1:添加一個目標部分this answer的完整答案。
太棒了!我錯過了'TouchDragInside'事件。我用'if let touch = ...',因爲我不確定強制解包是否會導致崩潰。 – Suragch