我想制作一些可拖动的UIView 但是在以下代码的情况下,您只能拖动最后添加的一个UIView。
我有这个代码。
LabelView类是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];
}
答案 0 :(得分:1)
您应该为所有视图应用getsture。然后更改方法。 _labelView.center = movedPoint;
至[sender view].center = movedPoint;
- (void)panAction:(UIPanGestureRecognizer *)sender
{
CGPoint p = [sender translationInView:self.view];
CGPoint movedPoint = CGPointMake(_labelView.center.x + p.x, _labelView.center.y + p.y);
[sender view].center = movedPoint;
[sender setTranslation:CGPointZero inView:self.view];
}
答案 1 :(得分:0)
您可以创建一个可变数组,然后将每个新视图添加到该数组中。您可以通过添加:
来完成此操作NSMutableArray *viewsArray = [[NSMutableArray alloc] init];
// after creating the custom view
[viewsArray addObject:customView];
然后,您可以在数组中的视图顶部添加平移手势,这样他们都使用平移手势
for(LabelView *l in viewsArray) {
[l addGestureRecognizer:panGestureRecognizer];
}
这会将UIPanGestureRecognizer添加到您在此答案开头创建的数组中的所有自定义视图。
希望这有帮助!