[英]Swapping images in IOS
我必须在一个屏幕上交换四个图像。 只能在左/右/上/下方向交换图像,不能在对角线交换图像。 例如,第一张图像可以与其右侧和下方的图像交换,第二张图像只能与其左侧和下方的图像交换,依此类推。 谁能帮我一下如何做。 谢谢
要添加拖放功能(假设这就是您的意思),您需要研究UIPanGestureRecognizer
添加滑动手势识别器。 当用户滑动时,确定哪个方向并处理图像交换。
[编辑]-想象一个分成四个相等部分的正方形。 左上部分的索引为零,右上部分的索引为1,左下部分的索引为2,最后右下部分的索引为3。下面的代码检查当前索引,并从中确定当前是否有图像可以进行交换,如果不进行交换,则不执行任何操作。
这段代码是从我的头上来的,所以可能会有语法错误,但是逻辑是合理的(我希望:D)。
- (void) viewDidLoad {
// turn on user interaction on the image view as its off by default.
[self.imageView setUserInteractionEnabled:TRUE];
UISwipeGestureRecognizer *recognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(handleSwipe:)];
[recognizer setDirection:(UISwipeGestureRecognizerDirectionRight | UISwipeGestureRecognizerDirectionDown | UISwipeGestureRecognizerDirectionLeft | UISwipeGestureRecognizerDirectionUp)];
[self.imageView addGestureRecognizer:recognizer];
self.currentImageIndex = 0;
self.images = [NSArray arrayWithObjects:[UIImage imageNamed:@"top-left"],[UIImage imageNamed:@"top-right"],[UIImage imageNamed:@"bottom-left"],[UIImage imageNamed:@"top-right"],nil];
}
-(void)handleSwipeFrom:(UISwipeGestureRecognizer *)recognizer {
if (recognizer.direction == UISwipeGestureRecognizerDirectionRight) {
if (self.currentImageIndex == 0 || self.currentImageIndex == 2) self.currentImageIndex++; // change to image to the right
else return; // do nothing
}
else if (recognizer.direction == UISwipeGestureRecognizerDirectionLeft) {
if (self.currentImageIndex == 1 || self.currentImageIndex == 3) self.currentImageIndex--; // change to the image to the left
else return; // do nothing
}
else if (recognizer.direction == UISwipeGestureRecognizerDirectionUp) {
if (self.currentImageIndex == 2 || self.currentImageIndex == 3) self.currentImageIndex -= 2; // change to the above image
else return; // do nothing
}
else if (recognizer.direction == UISwipeGestureRecognizerDirectionDown) {
if (self.currentImageIndex == 0 || self.currentImageIndex == 1) self.currentImageIndex += 2; // change to the above image
else return; // do nothing
}
[UIView animationWithDuration:0.5 animations:^{
[self.imageView setAlpha:0];
} completion^(BOOL finished){
if (finished) {
[UIView animationWithDuration:0.5 animations:^{
[self.imageView setImage[self.images objectAtIndex:self.currentImageIndex]];
[self.imageView setAlpha:1];
}];
}
}];
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.