简体   繁体   中英

Restrict dragging of a label out of its superView ios swift

I have an UIImageView inside of which there is a label whose text have to be move on pan gesture. Though I am able to drag the test but having problem in restricting the movement of text within the image view. The below code is for restricting movement in x direction whenever I try to implement similar approach to y direction two conditions arise at the corner which creates problem. Is there any better approach please help.

func dragText(sender: UIPanGestureRecognizer) {
        let translation = sender.translationInView(self.view)
        print(translation)
        switch sender.state {
        case .Changed:
            self.textLabelOriginX = (sender.view?.frame.origin.x)!

            if self.textLabelOriginX <= 10 {
                sender.view?.center = CGPointMake(sender.view!.center.x + 0.1, sender.view!.center.y + translation.y)
            } else if ((sender.view?.frame.origin.x)! + sender.view!.frame.width >= sender.view?.superview?.bounds.width) {
                sender.view?.center = CGPointMake(sender.view!.center.x - 0.1, sender.view!.center.y + translation.y)
            }
            else {
                sender.view?.center = CGPointMake(sender.view!.center.x + translation.x, sender.view!.center.y + translation.y)
            }

            sender.setTranslation(CGPointZero, inView: self.view)

        default:
            break
        }
    }

Core graphics has a lot of functions to check whether a rect is inside or outside a particular frame, union, intersection etc.
In the .Changed you can check if the translation you want to apply to the moving view is fully contained inside that specific rect or not.

bool CGRectContainsRect (
   CGRect rect1,
   CGRect rect2
);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM