Swift 4:防止UIView的子视图移动到它的父母之外

时间:2017-12-20 10:06:57

标签: ios swift uiview

我有一个UIView和一个半尺寸的SubView。用户可以在主视图周围移动子视图,这是我想要的,但问题是,当用户将UIView拖到MainView的角落时,子视图会消失,在它下面的父母,

Main UIView大小:105x105

SubView大小:35x35

请看一下这个样本

enter image description here

我想将子视图锁定在MainView之外,我通过以下代码实现了拖动:

override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
    let touch : UITouch = touches.first!

    self.subview.center = touch.location(in: imageview) // here

    if touch.view == self.imageview  {


    if touch.location(in: view).x >= 245 {

        self.rotateMe.transform = CGAffineTransform(rotationAngle: 1)

    } else {

        self.rotateMe.transform = CGAffineTransform(rotationAngle: -1)
    }

    }


}

但是我无法锁定子视图。

2 个答案:

答案 0 :(得分:1)

尝试这一点必须为你的requeriments工作

import UIKit

class DraggableView: UIView {

    var localTouchPosition : CGPoint?

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        super.touchesBegan(touches, with: event)
        let touch = touches.first
        self.localTouchPosition = touch?.preciseLocation(in: self)
    }

    override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
        super.touchesMoved(touches, with: event)
        let touch = touches.first
        guard let location = touch?.location(in: self.superview), let localTouchPosition = self.localTouchPosition else{
            return
        }

        let origin = CGPoint(x: location.x - localTouchPosition.x, y: location.y - localTouchPosition.y)
        if(origin.x >= 0 && origin.y >= 0){
            if(origin.x + self.bounds.size.width <= self.superview!.bounds.size.width && origin.y + self.bounds.size.height <= self.superview!.bounds.size.height)
            {
                self.frame.origin = origin
            }
        }
    }

    override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
        super.touchesEnded(touches, with: event)
        self.localTouchPosition = nil
    }

    override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) {
        super.touchesCancelled(touches, with: event)
        self.localTouchPosition = nil
    }

}

答案 1 :(得分:0)

将此作为答案 将这些条件放在父视图及其子视图

if (subview.origin.y + subview.size.height) > parentview.height { 
  subview.origin.y = parentview.size.height - subview.size.height 
} 
if (subview.origin.x + subview.size.width) > parentview.width { 
  subview.origin.x = parentview.size.width - subview.size.width 
} 
if (subview.origin.x < 0) {
  subview.origin.x = 0
}
if (subview.origin.y < 0) {
  subview.origin.y = 0
}