Это всего лишь вопрос использования распознавателей жестов (см. Event Handler Guide).
Фактические реализации немного зависят от того, как вы хотите это сделать. Вот случайный пример, когда у меня есть элемент управления с разделенным видом, и я перетаскиваю что-то из таблицы влево в виде справа, все перетаскивание, вызванное длинным нажатием (например, «нажмите и удерживайте»,). Таким образом, я просто создать жест распознаватель в viewDidLoad контроллера Tableview (в моем случае, контроллер представления мастер):
UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPress:)];
[self.tableView addGestureRecognizer:longPress];
И тогда я определил жест обработчик распознавателя, который реализует функцию перетаскивания, например,
- (IBAction)longPress:(UIGestureRecognizer *)sender
{
if (sender.state == UIGestureRecognizerStateBegan)
{
// figure out which item in the table was selected
NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:[sender locationInView:self.tableView]];
if (!indexPath)
{
inDrag = NO;
return;
}
inDrag = YES;
// get the text of the item to be dragged
NSString *text = [NSString stringWithString:[[_objects objectAtIndex:indexPath.row] description]];
// create item to be dragged, in this example, just a simple UILabel
UIView *splitView = self.splitViewController.view;
CGPoint point = [sender locationInView:splitView];
UIFont *font = [UIFont systemFontOfSize:12];
CGSize size = [text sizeWithFont:font];
CGRect frame = CGRectMake(point.x - (size.width/2.0), point.y - (size.height/2.0), size.width, size.height);
draggedView = [[UILabel alloc] initWithFrame:frame];
[draggedView setFont:font];
[draggedView setText:text];
[draggedView setBackgroundColor:[UIColor clearColor]];
// now add the item to the view
[splitView addSubview:draggedView];
}
else if (sender.state == UIGestureRecognizerStateChanged && inDrag)
{
// we dragged it, so let's update the coordinates of the dragged view
UIView *splitView = self.splitViewController.view;
CGPoint point = [sender locationInView:splitView];
draggedView.center = point;
}
else if (sender.state == UIGestureRecognizerStateEnded && inDrag)
{
// we dropped, so remove it from the view
[draggedView removeFromSuperview];
// and let's figure out where we dropped it
UIView *detailView = self.detailViewController.view;
CGPoint point = [sender locationInView:detailView];
UIAlertView *alert;
if (CGRectContainsPoint(detailView.bounds, point))
alert = [[UIAlertView alloc] initWithTitle:@"dropped in details view" message:nil delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil];
else
alert = [[UIAlertView alloc] initWithTitle:@"dropped outside details view" message:nil delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil];
[alert show];
}
}
Очевидно, что если вы перетаскиваете подвид из вашего Scrollview, вы бы заменить indexPathForRowAtPoint
логику с чем-то вроде:
UIView *objectToDrag = nil;
CGPoint point = [sender locationInView:myView];
for (UIView *control in myView.subviews)
if (CGRectContainsPoint(control.frame, point))
objectToDrag = control;
if (!objectToDrag)
{
inDrag = NO;
return;
}
Это поможет вам определить, что вы хотите перетащить, но оттуда логика очень похожа (за исключением, а не перетаскивания UILabel, как в моем примере, вы перетащите свой объектToDrag).
Вам просто нужно прочитать документацию разработчика, эта функциональность может быть реализована, что вы пробовали до сих пор? – rishi
До сих пор я могу перетащить изображение. Документацию немного трудно читать для меня. Я исхожу из javascript, html и css. И я изучаю эти все новые концепции, такие как объектно-ориентированное программирование, объективный c и так далее. Но медленно, я думаю, что могу это сделать. Я просто хотел, чтобы какой-то неплохой письменный учебник :). – 88fsantos