本文介绍了如何在iOS中拖动某些图像?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

想知道如何在屏幕上拖动图像以及将使用哪些代码。尝试查找,但只有旧版本的Swift有答案,不再有效。我想拖动图像,但不要将手指放在屏幕上,它会转到那个位置。只需拖动。

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 drag the image, but not place finger on screen and it goes to that spot. Just drag.

给我错误:



import UIKit

class DraggableImage: UIImageView {
    override func touchesMoved(touches: Set<uitouch>, withEvent event: UIEvent?) {
        if let touch = touches.first {
            let position = touch.locationInView(superview)
            center = CGPointMake(position.x, position.y)
        }
    }
}


推荐答案

你需要继承 UIImageView 并在init中你需要设置 userInteractionEnabled = true 然后重写此方法覆盖 func touchesMoved(触摸:设置< UITouch>,withEvent事件:UIEvent?)好吧,我的代码是这个:

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<UITouch>, 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<UITouch>, with event: UIEvent?) {
        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
        }
        self.frame.origin = CGPoint(x: location.x - localTouchPosition.x, y: location.y - localTouchPosition.y)
    }

    override func touchesEnded(_ touches: Set<UITouch>, 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
     }
     */

}

这就是它的样子

希望这会有所帮助

这篇关于如何在iOS中拖动某些图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-01 15:14