可拖动的UIView移动不平滑,只能拖动一小段距离(包括视频)



视频: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:

@IBAction func buttonAddSubviewTextTapped(_ sender: UIButton) {
let label = UIView()
label.frame = CGRect(x: 0, y: 0, width: 200, height: 21)
label.center = CGPoint(x: 160, y: 285)
label.backgroundColor = .red
self.viewImagePreview.addSubview(label)
self.viewImagePreview.bringSubviewToFront(label)
}

如何实现完全平滑的可拖动UIView?

使按钮创建的视图可在其父视图中拖动的最终解决方案:

@IBAction func buttonAddSubviewTextTapped(_ sender: UIButton) {
let panGesture = UIPanGestureRecognizer(target: self, action: #selector(draggedView(_:)))
let label = UIView()
label.frame = CGRect(x: 0, y: 0, width: 200, height: 21)
label.center = CGPoint(x: 160, y: 285)
label.backgroundColor = .red
label.isUserInteractionEnabled = true
label.addGestureRecognizer(panGesture)
self.viewImagePreview.addSubview(label)
self.viewImagePreview.bringSubviewToFront(label)
}

// Function to drag a view
@objc func draggedView(_ sender: UIPanGestureRecognizer) {
guard let createdView = sender.view else {return}
createdView.bringSubviewToFront(viewImagePreview)
if sender.state == .began || sender.state == .changed {
let point = sender.location(in: self.viewImagePreview)
if let parentView = self.viewImagePreview {
let superBounds = CGRect(x: parentView.bounds.origin.x, y: parentView.bounds.origin.y, width: parentView.bounds.size.width - 2, height: parentView.bounds.size.height - 2)
if (superBounds.contains(point)) {
let translation = sender.translation(in: parentView)
createdView.center = CGPoint(x: createdView.center.x + translation.x, y: createdView.center.y + translation.y)
sender.setTranslation(CGPoint.zero, in: parentView)
}
}
}
}

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")
}
}

同样适用于您的情况,

尝试更换

self.frame.origin = CGPoint(x: location!.x-self.frame.size.width/2, y: location!.y-self.frame.size.height/2);

self.center = location

最新更新