我尝试过这种方法
@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)
}
它正在工作,但问题是当我在多个图像上使用此方法时会产生一些问题,例如, 拖动一个图像并更改其位置但是当我单击并拖动第二个图像时。我的第一张照片回到原来的位置。 以下是我从滚动视图中获取的图像: 当我点击第二张图像时,第一张图像也会转到原始位置
我在这里拖动图片
答案 0 :(得分:8)
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
}
*/
}
答案 1 :(得分:7)
自动布局正在运行,将图像恢复到限制条件应该存在的位置。
解决此问题的最简单方法是在代码中创建图像,而不是在故事板中创建图像。
类似的东西:
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)
答案 2 :(得分:0)
在viewDidLoad()中设置手势并添加以下方法:
private Lazy<IIzuProxyService> _izuProxyService = new Lazy<IIzuProxyService>(() => new IzuProxyService() );
private IIzuProxyService IzuProxyService {
get {
return _izuProxyService.Value;
}
}