我尝试用swift手指演示移动按钮。
所以我写了一个像底部的类实现UIButton。 问题是移动时按钮会跳过一小段距离。
我想知道为什么?
谢谢!
import UIKit
class MoveAbleButton: UIButton {
override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {}
override func touchesCancelled(touches: Set<NSObject>!, withEvent event: UIEvent!) {}
override func touchesEnded(touches: Set<NSObject>, withEvent event: UIEvent) {}
override func touchesMoved(touches: Set<NSObject>, withEvent event: UIEvent) {
let touch = touches.first
if let touchTemp = touch {
let t = touchTemp as! UITouch
let point = t.locationInView(self)
let x = self.frame.origin.x + point.x
let y = self.frame.origin.y + point.y
let w = self.frame.width
let h = self.frame.height
self.frame = CGRectMake(x, y, w, h)
// let x = self.center.x + point.x
// let y = self.center.y + point.y
//
// let newCenter = CGPoint(x: x, y: y)
//
// self.center = newCenter
println("touchesMoved (\(point.x),\(point.y))")
}
}
}
答案 0 :(得分:0)
您需要在移动按钮之前计算按钮的左上角和触摸点之间的距离。 这是我的代码:
class MoveAbleButton: UIButton {
var distantX:CGFloat!
var distantY:CGFloat!
override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
distantX = ((touches.first as! UITouch).locationInView(self)).x
distantY = ((touches.first as! UITouch).locationInView(self)).y
}
override func touchesCancelled(touches: Set<NSObject>!, withEvent event: UIEvent!) {}
override func touchesEnded(touches: Set<NSObject>, withEvent event: UIEvent) {}
override func touchesMoved(touches: Set<NSObject>, withEvent event: UIEvent) {
let touch = touches.first
if let touchTemp = touch {
let t = touchTemp as! UITouch
let pointInSuperView = t.locationInView(self.superview)
let x = pointInSuperView.x - distantX
let y = pointInSuperView.y - distantY
let w = self.frame.width
let h = self.frame.height
self.frame = CGRectMake(x, y, w, h)
// let x = self.center.x + point.x
// let y = self.center.y + point.y
//
// let newCenter = CGPoint(x: x, y: y)
//
// self.center = newCenter
//println("touchesMoved (\(point.x),\(point.y))")
}
}
}