将平移手势限制为固定帧

时间:2019-03-06 15:05:32

标签: swift uipangesturerecognizer

我已经在StackOverflow上搜索了几天,但没有任何答案。

我有一个UIImageView,我试图能够在其内部移动标签。现在,我可以移动标签了,但是它超出了UIImageView的范围。

到目前为止,这是我的平移手势代码:

var initialCenter = CGPoint()

    @objc func userDragged(pan: UIPanGestureRecognizer) {

        guard let senderView = pan.view else { return }
        guard let parentView = senderView.superview else { return }

        let translation = pan.translation(in: imageHolder)

        if pan.state == .began {
            self.initialCenter = senderView.center
            print(self.initialCenter)
        }

        // update the position.
        if pan.state == .changed {

            let newCenter = CGPoint(x: initialCenter.x + translation.x, y: initialCenter.y + translation.y)
            senderView.center = newCenter

        } else if pan.state == .ended || pan.state == .cancelled {

            print("ended or cancelled")

            let finalCenter = CGPoint(x: senderView.center.x, y: senderView.center.y)
            senderView.center = finalCenter
        } else {
            senderView.center = initialCenter
        }
    }

1 个答案:

答案 0 :(得分:0)

您可能需要在此处将标签添加到imageView。

  override func viewDidAppear(_ animated: Bool) {
    // imageHolder is UIImageView.

    imageHolder.clipsToBounds = true
    imageHolder.backgroundColor = UIColor.black

    //the label is called labelView here

      imageHolder.addSubview(self.labelView)
      imageHolder.isUserInteractionEnabled = true
     self.labelView.isUserInteractionEnabled = true


}

enter image description here