UIPanGestureRecognizer以编程方式添加了UIView

时间:2018-02-25 12:18:47

标签: swift uipangesturerecognizer uilongpressgesturerecogni

你能帮我吗?我想在长压力手势后创建圆圈并使其在平移手势的同时仍然按手指在屏幕上移动。当手指从屏幕移开时,应从中移除圆圈。 使用长按手势创建圆形工作正常,只是它不会移动。代码如下:

    @IBAction func spaceLongPressed(_ guesture: UILongPressGestureRecognizer) {
    let location = guesture.location(in: space)
    var panGesture = UIPanGestureRecognizer()

    circleView = UIView(frame: CGRect(x: location.x - space.bounds.height/4, y: location.y - space.bounds.height/4, width: space.bounds.height/2, height: space.bounds.height/2))

    if guesture.state == .began {

        circleView.backgroundColor = UIColor.red
        circleView.isUserInteractionEnabled = true
        circleView.tag = 100
        circleView.layer.cornerRadius = circleView.bounds.height/2
        space.addSubview(circleView)

        panGesture = UIPanGestureRecognizer(target: space, action: #selector(didPan(sender:)))
        space.addGestureRecognizer(panGesture)

    }

    if guesture.state == .ended {
        if let viewWithTag = self.view.viewWithTag(100) {
            viewWithTag.removeFromSuperview()
        }
    }

}

@objc func didPan(sender: UIPanGestureRecognizer) {

    if sender.state == .began {
    let translation = sender.translation(in: sender.view)

    let changeX = (sender.view?.center.x)! + translation.x
    let changeY = (sender.view?.center.y)! + translation.y

    sender.view?.center = CGPoint(x: changeX, y: changeY)
    sender.setTranslation(CGPoint.zero, in: sender.view)
    }
}

对象“空间”属于UIButton类型 - 我想在按钮中创建圆圈。

1 个答案:

答案 0 :(得分:0)

无需为更新位置创建panGesture。使用长按手势可以获得相同的效果。 (我改变了上面的代码,尤其是创建时的视图帧。)

var circleView: UIView!

@IBAction func spaceLongPressed(_ guesture: UILongPressGestureRecognizer) {
    let location = guesture.location(in: view)
    let size = CGSize(width: 100, height: 100)
    circleView = UIView(frame: CGRect(origin: location, size: size))

    if guesture.state == .began {
        circleView.backgroundColor = UIColor.red
        circleView.isUserInteractionEnabled = true
        circleView.tag = 100
        circleView.layer.cornerRadius = circleView.bounds.height/2
        view.addSubview(circleView)
    }

    if guesture.state == .changed {
        let position = guesture.location(in: view)
        if let viewWithTag = self.view.viewWithTag(100) {
            viewWithTag.center = position
        }
    }

    if guesture.state == .ended {
        if let viewWithTag = self.view.viewWithTag(100) {
            viewWithTag.removeFromSuperview()
        }
    }
}

输出:

abc