将ImageView保持在屏幕范围内

时间:2019-02-28 15:24:01

标签: swift uikit bounds

我正在使用下面的代码将imageView / player保留在屏幕内。该代码大部分都起作用,但有时播放器会飞离屏幕并完全消失。我正在使用UIPanGestureRecognizer在屏幕上移动图像。使用 Swift和UIKit ,如何在没有图像飞出屏幕的情况下将图像保持在屏幕范围内的百分之一百?

@objc func panFunction(_ sender: UIPanGestureRecognizer) {

    if sender.state == .began || sender.state == .changed {

        let translation = sender.translation(in: sender.view)

        let changeX = (sender.view?.center.x)! + translation.x
        let changeY = (sender.view?.center.y)! + translation.y
        let senderWidth = sender.view!.bounds.width / 2
        let senderHeight = sender.view!.bounds.height / 2
        sender.view?.center = CGPoint(x: changeX, y: changeY)

        if changeX <= senderWidth {
            sender.view!.center = CGPoint(x: senderWidth, y: sender.view!.center.y + translation.y)

        }else

            if changeX >= self.view.bounds.maxX - senderWidth {
                sender.view!.center = CGPoint(x: self.view.bounds.maxX - senderWidth, y: sender.view!.center.y + translation.y)
        }

        if changeY <= senderHeight {
            sender.view!.center = CGPoint(x: sender.view!.center.x + translation.x, y: senderHeight)

        }else

            if changeY >= self.view.bounds.maxY - senderHeight {
                sender.view!.center = CGPoint(x: sender.view!.center.x + translation.x, y: self.view.bounds.maxY - senderHeight)

            }else{
                sender.view!.center = CGPoint(x: sender.view!.center.x + translation.x, y: sender.view!.center.y + translation.y)
        }

        sender.setTranslation(CGPoint.zero, in: self.view)

0 个答案:

没有答案