我有UIScrollView包含许多UIImageViews。我需要将UIImage从UIScrollView拖到另一个视图。但我的代码只在UIScrollView中拖动。我无法将图像拖到scrollView外部。请帮帮我..我的代码是......
for (int i = 0; i < [myArray count]; i++) {
image = [[UIImageView alloc]initWithFrame:CGRectMake(0, y, 75, 30)];
image.userInteractionEnabled = YES;
image.backgroundColor = [UIColor blueColor];
UIPanGestureRecognizer *panRecg = [[UIPanGestureRecognizer alloc]initWithTarget:self action:@selector(labelDragged:)];
[image addGestureRecognizer:panRecg];
y=y+35;
[gScrollView addSubview:image];
}
-(void)labelDragged:(UIPanGestureRecognizer *)recognizer {
UIImageView *imageView = (UIImageView *)recognizer.view;
CGPoint newCenter = [recognizer translationInView:self.view];
if([recognizer state] == UIGestureRecognizerStateBegan) {
beginX = imageView.center.x;
beginY = imageView.center.y;
}
newCenter = CGPointMake(beginX + newCenter.x, beginY + newCenter.y);
[imageView setCenter:newCenter];
}
答案 0 :(得分:2)
有几点意见:
将其从滚动视图中拖出时,您希望将其从滚动视图中删除并将其添加到例如self.view
。然后,您将执行addSubview
并相应地调整坐标:
newCenter = [self.view convertPoint:newCenter fromView:imageView.superview];
[self.view addSubview:imageView];
imageView.center = newCenter;
确保将滚动视图的clipsToBounds
设置为NO,以便在拖动时继续查看。
注意,我已将此更改为引用imageView.superview
而不是滚动视图。如果在那里保留scrollview引用,则必须添加条件检查以确保图像视图尚未从滚动视图移开。
答案 1 :(得分:1)
我在评论中为您提供了几个UI问题,但@Rob是正确的,即在层次结构中移动视图的外观的关键是实际在层次结构中移动它。拖动开始时......
CGRect newFrame = [gScrollView convertRect:imageView.frame toView:self.view];
imageView.frame = newFrame;
[self.view addSubview:imageView];
手势识别器应保持完整。
答案 2 :(得分:1)
以下是拖动
的方法-(void)labelDragged:(UIPanGestureRecognizer *)recognizer {
{
UIImageView *imageView=(UIButton *)[recognizer view];
CGPoint newCenter = [recognizer translationInView:self.view];
if (recognizer.state==UIGestureRecognizerStateBegan) {
CGRect rect=[self.view convertRect:[imageView frame] fromView:[imageView superview]];
beginX = imageView.center.x;
beginY = imageView.center.y;
[vew setFrame:rect];
[self.view addSubview:vew];
}
else
{
CGRect rect=imageView.frame;
newCenter.x=(newCenter.x+Begin.x);
newCenter.y=(newCenter.y+Begin.y);
imageView.center=newCenter;
if (CGRectIntersectsRect(rect, [AcceptingView frame])) {
[AcceptingView setBackgroundColor:[UIColor lightGrayColor]];//Notifying that the AcceptingView will accept the icon
}
else
{
//change back to old color
}
}
if (recognizer.state==UIGestureRecognizerStateEnded)
{
CGRect rect=[imageView frame];
if (CGRectIntersectsRect(rect, [AcceptingView frame])) {
//your method of adding the Image to acceptView
CGRect rect=[acceptView bounds];
rect.size=imageView.frame.size;
imageView.frame=rect;
[AcceptingView addSubView:imageView];
}
else//else part is means for if user drop the dragged view somewhere else other than AcceptingView
{
//add image back to scrollView
}
}
}