IOS 5.1拖放
我是IOS的noob。 我已经search了很多,但我没有find任何有关在IOS上拖放的好教程。 我刚才读到的是没有直接的支持。 这是可能的拖动一个项目从滚动视图到一个视图,并传递一些信息呢? 想象一下MAIL应用程序。 我想把电子邮件拖到右边的大视图上,并传递一些信息。 有没有任何书或教程可以教我如何制作它?
TKS!
这只是使用手势识别器(请参阅事件处理程序指南 )。
实际的实现取决于你想如何做。 这里有一个随机的例子,我有一个分割视图控件,我把东西从左边的tableview拖到右边的视图中,通过长按触发整个拖放(例如,“点击并按住” )。 因此,我只是在tableview控制器的viewDidLoad(在我的情况下,主视图控制器)中创build一个手势识别器:
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
replaceindexPathForRowAtPoint
逻辑:
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(除了我的示例)之外,您还需要拖动objectToDrag)。