如何在swift 3中拖动其他View中的视图?

时间:2018-01-22 08:42:17

标签: ios swift

我想在swift 3中拖动其他View 中的视图。我搜索了很多方法,但它们都是Objective-C。

欢迎任何swift的帮助。

由于

2 个答案:

答案 0 :(得分:0)

oldView.addSubview(newView)
newView.leftAnchor.constrains(equalTo: oldView.leftAnchor).isActive = true
newView.rightAnchor.constrains(equalTo: oldView.rightAnchor).isActive = true
newView.topAnchor.constrains(equalTo: oldView.topAnchor).isActive = true
newView.bottomAnchor.constrains(equalTo: oldView.bottomAnchor).isActive = true

答案 1 :(得分:0)

您可以通过以下方式实现相同目的:

   @IBAction func handlePan(_ recognizer: UIPanGestureRecognizer) {
        let translation: CGPoint = recognizer.translation(in: view)
        let recognizerFrame: CGRect? = recognizer.view?.frame
        recognizerFrame?.origin.x += translation.x
        recognizerFrame?.origin.y += translation.y
        if view.bounds.contains(recognizerFrame) {
            recognizer.view?.frame = recognizerFrame
        }
        else {
            // Check vertically
            if recognizerFrame?.origin.y < view.bounds.origin.y {
                recognizerFrame?.origin.y = nil
            }
            else if recognizerFrame?.origin.y + recognizerFrame?.size.height > view.bounds.size.height {
                recognizerFrame?.origin.y = view.bounds.size.height - recognizerFrame?.size.height
            }

            if recognizerFrame?.origin.x < view.bounds.origin.x {
                recognizerFrame?.origin.x = nil
}
    else if recognizerFrame?.origin.x + recognizerFrame?.size.width > view.bounds.size.width {
                recognizerFrame?.origin.x = view.bounds.size.width - recognizerFrame?.size.width
            }

        recognizer.setTranslation(CGPoint(x: 0, y: 0), in: view)
    }