视频:https://www.youtube.com/watch?v=8_xCTJAld9Y&feature=youtu.be。在这里您可以看到我的问题,但我不知道到底是哪里错了。我无法随意移动它。
我有一个可拖动的UIView,它具有一个自定义类:
import UIKit
class UIViewDraggable: UIView {
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.isUserInteractionEnabled = true
}
override init(frame: CGRect) {
super.init(frame: frame)
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
let touch = touches.first;
let location = touch?.location(in: self.superview);
if(location != nil)
{
self.frame.origin = CGPoint(x: location!.x-self.frame.size.width/2, y: location!.y-self.frame.size.height/2);
}
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
}
}
我通过点击按钮创建UIView:
import UIKit
class UIViewDraggable: UIView {
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.isUserInteractionEnabled = true
}
override init(frame: CGRect) {
super.init(frame: frame)
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
let touch = touches.first;
let location = touch?.location(in: self.superview);
if(location != nil)
{
self.frame.origin = CGPoint(x: location!.x-self.frame.size.width/2, y: location!.y-self.frame.size.height/2);
}
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
}
}
如何实现完全平滑的可拖动UIView?
向视图添加panGesture
,然后根据触摸位置更新view.center
let pan = UIPanGestureRecognizer(target: self, action: #selector(panView))
self.addGestureRecognizer(pan)
然后将其用作:
@objc func panView(pan: UIPanGestureRecognizer) {
let location = pan.location(in: self.superView) // get pan location
switch pan.state {
case .began:
print("began")
case .changed:
self.center = location
// updated your frames here
default:
print("nothing")
}
}