我在我的项目中遇到问题我的项目目的是UIImages
在开始时添加许多图像,这些图像应该可以拖放,因为我使用UIPanGestureRecognizer
但仍然遇到问题请帮助我提前谢谢。
这段代码在我的viewdidload
方法中
UIView *holderView = [[UIView alloc]init];
for (int i = 0; i<=4; i+=1) {
NSMutableArray * images = [[NSMutableArray alloc]initWithObjects:@"iphone-status-bar.png",@"uiswitch.png",@"NavigationBar.png",@"barbutton.png",@"ios-back-button.png", nil];
NSString * image_name= [NSString stringWithFormat:@"%@",[images objectAtIndex:i]];
// NSLog(@"%@",image_name);
UIImage *image = [UIImage imageNamed:image_name];
holderView = [[UIView alloc] initWithFrame:CGRectMake(2, i*30, image.size.width, image.size.height)];
UIImageView *imageview = [[UIImageView alloc] initWithFrame:[holderView frame]];
imageview.userInteractionEnabled = YES;
[imageview setImage:image];
[holderView addSubview:imageview];
UIPanGestureRecognizer *panRecognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(move:)];
[panRecognizer setMinimumNumberOfTouches:1];
[panRecognizer setMaximumNumberOfTouches:1];
[panRecognizer setDelegate:self];
[holderView addGestureRecognizer:panRecognizer];
[self.view addSubview:holderView];
}
手势处理程序是:
-(void)move:(id)sender {
[self.view bringSubviewToFront:[(UIPanGestureRecognizer*)sender view]];
CGPoint translatedPoint = [(UIPanGestureRecognizer*)sender translationInView:self.view];
if([(UIPanGestureRecognizer*)sender state] == UIGestureRecognizerStateBegan) {
firstX = [[sender view] center].x;
firstY = [[sender view] center].y;
}
translatedPoint = CGPointMake(firstX+translatedPoint.x, firstY+translatedPoint.y);
[[sender view] setCenter:translatedPoint];
if([(UIPanGestureRecognizer*)sender state] == UIGestureRecognizerStateEnded) {
CGFloat finalX = translatedPoint.x + (.01*[(UIPanGestureRecognizer*)sender velocityInView:self.view].x);
CGFloat finalY = translatedPoint.y + (.01*[(UIPanGestureRecognizer*)sender velocityInView:self.view].y);
if(UIDeviceOrientationIsPortrait([[UIDevice currentDevice] orientation])) {
if(finalX < 0) {
finalX = 0;
}
else if(finalX > 768) {
finalX = 768;
}
if(finalY < 0) {
finalY = 0;
}
else if(finalY > 1024) {
finalY = 1024;
}
}
else {
if(finalX < 0) {
finalX = 0;
}
else if(finalX > 1024) {
finalX = 768;
}
if(finalY < 0) {
finalY = 0;
}
else if(finalY > 768) {
finalY = 1024;
}
}
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:.35];
[UIView setAnimationCurve:UIViewAnimationCurveEaseOut];
[[sender view] setCenter:CGPointMake(finalX, finalY)];
[UIView commitAnimations];
}
}