使用swift在屏幕上拖动图像

Uma*_*zal 8 iphone ios swift xcode6

我试过这种方法

@IBAction func handlePan(recognizer:UIPanGestureRecognizer) {

 let translation = recognizer.translationInView(self.view)
 if let view = recognizer.view {
  view.center = CGPoint(x:view.center.x + translation.x,
                        y:view.center.y + translation.y)
}
 recognizer.setTranslation(CGPointZero, inView: self.view)
}
Run Code Online (Sandbox Code Playgroud)

它工作但问题是,当我在多个图像上使用此方法时,它会产生一些问题,例如,拖动一个图像并更改其位置但是当我单击并拖动第二个图像时.我的第一张照片回到原来的位置.以下是我从滚动视图中获取的图像:当我点击第二张图像时,第一张图像也会转到原始位置

在此输入图像描述

我在这里拖动图像很好

在此输入图像描述

Sac*_*mbh 9

class DraggableImageView: UIImageView {


var dragStartPositionRelativeToCenter : CGPoint?

override init(image: UIImage!) {
    super.init(image: image)

    self.userInteractionEnabled = true   //< w00000t!!!1

    addGestureRecognizer(UIPanGestureRecognizer(target: self, action: "handlePan:"))

    layer.shadowColor = UIColor.blackColor().CGColor
    layer.shadowOffset = CGSize(width: 0, height: 3)
    layer.shadowOpacity = 0.5
    layer.shadowRadius = 2
}

required init?(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
}

func handlePan(nizer: UIPanGestureRecognizer!) {
    if nizer.state == UIGestureRecognizerState.Began {
        let locationInView = nizer.locationInView(superview)
        dragStartPositionRelativeToCenter = CGPoint(x: locationInView.x - center.x, y: locationInView.y - center.y)

        layer.shadowOffset = CGSize(width: 0, height: 20)
        layer.shadowOpacity = 0.3
        layer.shadowRadius = 6

        return
    }

    if nizer.state == UIGestureRecognizerState.Ended {
        dragStartPositionRelativeToCenter = nil

        layer.shadowOffset = CGSize(width: 0, height: 3)
        layer.shadowOpacity = 0.5
        layer.shadowRadius = 2

        return
    }

    let locationInView = nizer.locationInView(superview)

    UIView.animateWithDuration(0.1) {
        self.center = CGPoint(x: locationInView.x - self.dragStartPositionRelativeToCenter!.x,
            y: locationInView.y - self.dragStartPositionRelativeToCenter!.y)
    }
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func drawRect(rect: CGRect) {
// Drawing code
}
*/   
}
Run Code Online (Sandbox Code Playgroud)


vac*_*ama 8

自动布局正在运行,将图像放回到约束所应该的位置.

解决此问题的最简单方法是在代码中创建图像,而不是在Storyboard中创建它们.

就像是:

let lightBulb = UIImageView(frame: CGRectMake(100, 100, 50, 50))
lightBulb.image = UIImage(named: "lightBulb")
lightBulb.contentMode = .ScaleToFill
lightBulb.userInteractionEnabled = true

lightBulb.addGestureRecognizer(UIPanGestureRecognizer(target: self, action: "handlePan:"))

self.view.addSubview(lightBulb)
Run Code Online (Sandbox Code Playgroud)