Cocoa Touch - moving UIImageView on the screen

What an easy way to let users drag and drop a UIImageView around to place it of their choice. This is a photo app.

Thank!

+3
source share
1 answer

First, create a container view that will touch touch events. Then you need a subclass of UIIMageView that will make sure that when you set the center of the object, it does not exit the screen.

I made such a class some time ago, here is the code (it can also be animated).

.h

#import <UIKit/UIKit.h>

@interface ObjectView : UIImageView 
{
}

-(void) setCenter: (CGPoint) center inBounds: (CGRect) bounds withAnimation: (BOOL) animate;

@end

.m

#import "ObjectView.h"

@implementation ObjectView

#define MOVE_TO_CENTER_DURATION 0.1
-(void) setCenter: (CGPoint) center inBounds: (CGRect) bounds withAnimation: (BOOL) animate
{
    CGRect frame = self.frame;

    if(center.x + frame.size.width/2 > bounds.origin.x + bounds.size.width) 
        center.x -= ((center.x + frame.size.width/2) - (bounds.origin.x + bounds.size.width));
    else if(center.x - frame.size.width/2 < bounds.origin.x) 
        center.x += bounds.origin.x - (center.x - frame.size.width/2);

    if(center.y + frame.size.height/2 > bounds.origin.y + bounds.size.height) 
        center.y -= (center.y + frame.size.height/2) - (bounds.origin.y + bounds.size.height);
    else if(center.y - frame.size.height/2 < bounds.origin.y) 
        center.y += bounds.origin.y - (center.y - frame.size.height/2);

    if(animate) {
        [UIView beginAnimations:nil context:NULL];
        [UIView setAnimationDuration: MOVE_TO_CENTER_DURATION];
    }

    self.center = center;

    if(animate)
        [UIView commitAnimations];

} 

@end

Hope this helps a bit!

+2
source

Source: https://habr.com/ru/post/1755200/


All Articles