4

make a UIV view of drag

 2 years ago
source link: https://www.codesd.com/item/make-a-uiv-view-of-drag.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

make a UIV view of drag

advertisements

I'd like to make some drag-able UIView.
But in case of following code, you can drag only one UIView you have added at the last.

J3Dkg.png

I have this code.
LabelView class is subclass of UIView.

ViewControlle.h

@interface ViewController : UIViewController

@property (nonatomic, strong) LabelView* labelView;

@end

ViewController.m

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];

    _labelView = [[LabelView alloc]initWithFrame:CGRectMake(100, 200, 200, 50)];
    [self.view addSubview:_labelView];

    UIPanGestureRecognizer* pan = [[UIPanGestureRecognizer alloc]initWithTarget:self action:@selector(panAction:)];
    [_labelView addGestureRecognizer:pan];

    UIButton* addButton = [[UIButton alloc]initWithFrame:CGRectMake(270, 60, 40, 40)];
    [addButton addTarget:self action:@selector(newLabelView) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:addButton];
}

- (void)panAction:(UIPanGestureRecognizer *)sender
{
    CGPoint p = [sender translationInView:self.view];
    CGPoint movedPoint = CGPointMake(_labelView.center.x + p.x, _labelView.center.y + p.y);
    _labelView.center = movedPoint;
    [sender setTranslation:CGPointZero inView:self.view];
}

- (void)newLabelView
{
    _labelView = [[LabelView alloc]initWithFrame:CGRectMake(20, 60, 200, 50)];
    [self.view addSubview:_labelView];
    UIPanGestureRecognizer* pan = [[UIPanGestureRecognizer alloc]initWithTarget:self action:@selector(panAction:)];
    [_labelView addGestureRecognizer:pan];
}


You could create a mutable array, and then add each new view into that array. You do this by adding:

NSMutableArray *viewsArray = [[NSMutableArray alloc] init];
// after creating the custom view
[viewsArray addObject:customView];

Then, you can add a pan gesture on top of the views in the array, that way they are all using the pan gesture

for(LabelView *l in viewsArray) {
    [l addGestureRecognizer:panGestureRecognizer];
}

this will add a UIPanGestureRecognizer to all the custom views in the array that you created in the beginning of this answer.

Hope this helps!


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK