Tinder-подобная анимация смахивания для iOS

Я следовал этому очень полезному руководству о том, как добавить смахивание в стиле Tinder (http://guti.in/articles/creating-tinder-like-animations/); однако у меня есть одна проблема - когда изображение исчезает, я хочу заменить его другим изображением. Как/где это сделать?


person Connor    schedule 04.04.2014    source источник
comment
Проще всего было бы добавить еще одно перетаскиваемое представление под первым. Затем вы просто чередуете их. (При перетаскивании первого, второй сидит на своем месте, пока первый не утащит и наоборот). Таким образом, 2 одинаковых вида, и вы просто чередуете, какой из них вы перетаскиваете, а какой скрыт.   -  person Dima    schedule 04.04.2014
comment
github.com/modocache/MDCSwipeToChoose Это может сэкономить вам время.   -  person Tim    schedule 20.06.2014
comment
попробуйте это github.com/nickypatson/TinderSwipeView   -  person nickypatson    schedule 09.01.2018


Ответы (3)


Я построил более простой и полный проект на основе этого руководства. В частности, вы можете использовать массив изображений и назначить каждой карточке изображение на основе индекса изображения. Будут ли изображения динамическими или статичными?

На данный момент это может не помочь, но в любом случае вот: https://github.com/cwRichardKim/TinderSimpleSwipeCards

person cwRichardKim    schedule 20.06.2014

проверить это, написано в Swift 4

https://github.com/nickypatson/TinderSwipeView

func beDragged(_gestureRecognizer: UIPanGestureRecognizer) {

    xFromCenter = gestureRecognizer.translation(in: self).x
    yFromCenter = gestureRecognizer.translation(in: self).y
    switch gestureRecognizer.state {
    //%%% just started swiping
    case .began:
        originalPoint = self.center;
        break;

    //%%% in the middle of a swipe
    case .changed:
        let rotationStrength = min(xFromCenter / ROTATION_STRENGTH, ROTATION_MAX)
        let rotationAngel = .pi/8 * rotationStrength
        let scale = max(1 - fabs(rotationStrength) / SCALE_STRENGTH, SCALE_MAX)
        center = CGPoint(x: originalPoint.x + xFromCenter, y: originalPoint.y + yFromCenter)
        let transforms = CGAffineTransform(rotationAngle: rotationAngel)
        let scaleTransform: CGAffineTransform = transforms.scaledBy(x: scale, y: scale)
        self.transform = scaleTransform
        updateOverlay(xFromCenter)
        break;

    case .ended:
        afterSwipeAction()
        break;

    case .possible:break
    case .cancelled:break
    case .failed:break
    }
}

let panGestureRecognizer = UIPanGestureRecognizer (цель: я, действие: #selector (self.beingDragged)) addGestureRecognizer (panGestureRecognizer)

Надеюсь, это сработает. Дайте мне знать

Благодарность

person nickypatson    schedule 09.01.2018

этот ответ основан на коде/ответе от cwRichardKim (спасибо, cwRichardKim!). я не нашел руководство, как добавить изображения на каждую карту. вставив мой подход ниже (в этом примере URL-адрес изображения жестко закодирован, но в реальном приложении можно получить URL-адрес изображения из облака):

в DraggableView.h:

@property (nonatomic,strong)UIImageView* photoImageView; //%%% a placeholder for member photo to place on card

в DraggableView.m:

...
@synthesize photoImageView;
... 
// - (id)initWithFrame:(CGRect)frame ...
// add photo to card
        //You need to specify the frame of the view
        UIView *photoView = [[UIView alloc] initWithFrame:CGRectMake(0,0,self.frame.size.width,self.frame.size.width)];
        photoImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"place_holder_image.png"]];
        // UIImageView *imageView = [[UIImageView alloc] initWithImage:photo];
        //specify the frame of the imageView in the superview , here it will fill the superview
        photoImageView.frame = photoView.bounds;
        // add the imageview to the superview
        [photoView addSubview:photoImageView];
        //add the view to the main view
        [self addSubview:photoView];

в DraggableViewBackground.h:

@property(retain,nonatomic)NSArray* exampleCardUrls;

в DraggableViewBackground.m:

...
@synthesize exampleCardUrls;
...
exampleCardUrls = [[NSArray alloc]initWithObjects:@"http://images.clipartpanda.com/clipart-people-nTBX8zkgc.jpeg",@"http://epilepsyu.com/wp-content/uploads/2014/01/happy-people.jpg",@"http://alivecampus.com/wp-content/uploads/2014/09/people-02.jpg",@"https://www.google.com/images/srpr/logo11w.png",@"http://modalpoint.com/wp-content/uploads/2014/11/people-blue-stick-people-hi.png", nil];
...
// ... -(DraggableView *)createDraggableViewWithDataAtIndex:(NSInteger)index ...
// retrieve image for cell in background
    NSURL *url = [NSURL URLWithString:exampleCardUrls[index]];
    [self loadImage:url withIndex:index];
...
#pragma mark - cloud, load image
- (void)loadImage:(NSURL *)imageURL withIndex:(NSInteger)index
{
    // create array of objects to pass to next method
    NSMutableArray* params = [[NSMutableArray alloc]init];
    [params addObject:imageURL];
    NSNumber *indexNumber = [NSNumber numberWithInt:index];
    [params addObject:indexNumber];

    NSOperationQueue *queue = [NSOperationQueue new];
    NSInvocationOperation *operation = [[NSInvocationOperation alloc]
                                        initWithTarget:self
                                        selector:@selector(requestRemoteImage:)
                                        object:params];
    [queue addOperation:operation];
}

- (void)requestRemoteImage:(NSMutableArray*)params
{
    // get data from params
    NSURL* imageURL = params[0];

    NSData *imageData = [[NSData alloc] initWithContentsOfURL:imageURL];
    UIImage *image = [[UIImage alloc] initWithData:imageData];
    params[0] = image;

    [self performSelectorOnMainThread:@selector(placeImageInUI:) withObject:params waitUntilDone:YES];
}

- (void)placeImageInUI:(NSArray*)params
{
    // get data from params
    UIImage* image = params[0];
    NSNumber* indexNumber = params[1];
    NSInteger index = [indexNumber integerValue];

    DraggableView* myDraggableView = allCards[index];
    myDraggableView.photoImageView.image = image;
    allCards[index] = myDraggableView;

}
person tmr    schedule 04.04.2015