斯威夫特 2.0:
尝试: -
override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
view.endEditing(true)
super.touchesBegan(touches, withEvent: event)
//make condition here
}
或者
使用 UIPanGestureRecognizer。在 ViewController 中,将识别器安装在“父”视图上。
var pan = UIPanGestureRecognizer(target:self, action:"pan:")
pan.maximumNumberOfTouches = 1
pan.minimumNumberOfTouches = 1
self.view.addGestureRecognizer(pan)
在识别器动作中,首先抓取事件的位置。然后,根据识别器的状态,实现拖动功能的不同部分。
func pan(rec:UIPanGestureRecognizer) {
var p:CGPoint = rec.locationInView(self.view)
var center:CGPoint = CGPointZero
switch rec.state {
case .Began:
println("began")
self.selectedView = view.hitTest(p, withEvent: nil)
if self.selectedView != nil {
self.view.bringSubviewToFront(self.selectedView!)
}
case .Changed:
if let subview = selectedView {
center = subview.center
var distance = sqrt(pow((center.x - p.x), 2.0) + pow((center.y - p.y), 2.0))
println("distance \(distance)")
if subview is MyView {
if distance > threshold {
if shouldDragX {
subview.center.x = p.x - (p.x % snapX)
}
if shouldDragY {
subview.center.y = p.y - (p.y % snapY)
}
}
}
}
case .Ended:
if let subview = selectedView {
if subview is MyView {
// do whatever
}
}
// must do this of course
selectedView = nil
}