How to drag certain image in iOS?

前端 未结 2 513
野趣味
野趣味 2020-12-22 14:42

Wanted to know how I can drag a image across screen and what code would be used. Tried looking up but only older versions of Swift have answer and no longer work. I want to

2条回答
  •  醉梦人生
    2020-12-22 15:03

    You need to subclass UIImageView and in the init you need to set userInteractionEnabled = true and then override this method override func touchesMoved(touches: Set, withEvent event: UIEvent?) well, my code is this:

        class DraggableImage: UIImageView {
    
        var localTouchPosition : CGPoint?
    
        required init?(coder aDecoder: NSCoder) {
            super.init(coder: aDecoder)
            self.layer.borderWidth = 1
            self.layer.borderColor = UIColor.red.cgColor
            self.isUserInteractionEnabled = true
        }
    
        override func touchesBegan(_ touches: Set, with event: UIEvent?) {
            let touch = touches.first
            self.localTouchPosition = touch?.preciseLocation(in: self)
        }
    
        override func touchesMoved(_ touches: Set, 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
            }
            self.frame.origin = CGPoint(x: location.x - localTouchPosition.x, y: location.y - localTouchPosition.y)
        }
    
        override func touchesEnded(_ touches: Set, with event: UIEvent?) {
            self.localTouchPosition = nil
        }
        /*
         // Only override drawRect: if you perform custom drawing.
         // An empty implementation adversely affects performance during animation.
         override func drawRect(rect: CGRect) {
         // Drawing code
         }
         */
    
    }
    

    This is how it looks

    Hope this helps

提交回复
热议问题