为什么BringSubviewToFront()仅适用于平移,而不是轻按?

时间:2019-03-28 12:33:40

标签: swift xcode swift4

view.bringSubviewToFront(tappedView)
当我拖动(平移)视图时,

起作用,但是当我点击它们时却不起作用。我的问题是,当我在一个视图上叠加另一个视图时,我希望在点击时底部视图位于前面。目前,只有在拖动时它才会位于最前面。我是否需要一些其他代码来做到这一点?谢谢。

这是我的代码的摘录,内容更多:

@objc func didPan(_ recognizer: UIPanGestureRecognizer) {
        let location = recognizer.location(in: self.view)
            switch recognizer.state {
            case .began:
                currentTappedView = moviePieceView.filter { pieceView -> Bool in
                    let convertedLocation = view.convert(location, to: pieceView)
                    return pieceView.point(inside: convertedLocation, with: nil)
                    }.first
                currentTargetView = movieTargetView.filter { $0.pieceView == currentTappedView }.first
            case .changed:
                guard let tappedView = currentTappedView else { return }
                let translation = recognizer.translation(in: self.view)
                tappedView.center = CGPoint(x: tappedView.center.x + translation.x, y: tappedView.center.y + translation.y)
                recognizer.setTranslation(.zero, in: view)
                view.bringSubviewToFront(tappedView)
    ```

2 个答案:

答案 0 :(得分:0)

我遇到了同样的问题,我设法通过以下方式解决了这个问题:

  

在视图中添加一个手势识别器,并将其放入代码中。 在将其附加到代码时不要忘记设置委托!

@IBAction func tappedView1(recognizer: UITapGestureRecognizer) {
        view.bringSubviewToFront(myView)
    }
  

将其放入您的viewDidLoad:

  let tap = UITapGestureRecognizer(target: self, action: #selector(tappedView1))
        tap.cancelsTouchesInView = false
        self.view.addGestureRecognizer(tap)

如果要通过panGesture进行操作,请检查我的question

答案 1 :(得分:0)

谢谢大家。当我编写了didPan()之外的第二个函数时,它起作用了。

这是附加代码:

    override func viewDidLoad() {
        super.viewDidLoad()
        configureLabel()

        let panGestureRecognizer = UIPanGestureRecognizer(target: self, action: #selector(didPan(_:)))
        view.addGestureRecognizer(panGestureRecognizer)

        let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(didTap(_:)))
            view.addGestureRecognizer(tapGestureRecognizer)
    }

    @objc func didTap(_ recognizer: UITapGestureRecognizer) {
        let location = recognizer.location(in: self.view)
        currentTappedView = moviePieceView.filter { pieceView -> Bool in
            let convertedLocation = view.convert(location, to: pieceView)
            return pieceView.point(inside: convertedLocation, with: nil)
            }.first
        guard let tappedView = currentTappedView else { return }
        view.bringSubviewToFront(tappedView)
    }

但是,我发现,如果您不想通过编程方式进行操作,也可以在“图像视图”中勾选“已启用用户交互”框。