Xamarin.iOSでドラッグアンドドロップが可能なViewを配置する

By | 2013/04/22
Pocket

public class MyDraggableImage : UIImageView
{
	public MyDraggableImage(RectangleF frame) : base(frame)
	{
	}
 
	public PointF StartLocation { get; set; }
}
public override void TouchesBegan (NSSet touches, UIEvent evt)
{
	var pt = (touches.AnyObject as UITouch).LocationInView(this);
	StartLocation = pt;
	this.Superview.BringSubviewToFront(this);
}
 
public override void TouchesMoved (NSSet touches, UIEvent evt)
{
	// Move relative to the original touch point 
	var pt = (touches.AnyObject as UITouch).LocationInView(this);
	var frame = this.Frame;
	frame.X += pt.X - StartLocation.X;
	frame.Y += pt.Y - StartLocation.Y;
	this.Frame = frame;
}
 
public override void TouchesEnded (NSSet touches, UIEvent evt)
{
	// Move relative to the original touch point 
	var pt = (touches.AnyObject as UITouch).LocationInView(this);
	var frame = this.Frame;
	frame.X += pt.X - StartLocation.X;
	frame.Y += pt.Y - StartLocation.Y;
	this.Frame = frame;
}
var image = UIImage.FromFile("myImage.png");
var draggableRect = new RectangleF(0f, 0f, image.Size.Width, image.Size.Height);
var dragger = new MyDraggableImage(draggableRect);
dragger.Image = image;
dragger.UserInteractionEnabled = true;
view.AddSubview(dragger);