Перетаскиваемый UIView не перемещается плавно, его можно перетаскивать только на небольшое расстояние (видео включено) - PullRequest
0 голосов
/ 20 февраля 2020

Видео: 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)

            }
        }
    }
}

1 Ответ

1 голос
/ 20 февраля 2020

Добавьте panGesture к вашему View, а затем на основе сенсорного местоположения обновите ваш 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
...