gpt4 book ai didi

ios - 制作一些可拖动的 UIView

转载 作者:行者123 更新时间:2023-11-29 02:55:23 26 4
gpt4 key购买 nike

我想做一些可拖动的 UIView。
但是如果是下面的代码,你只能拖动你最后添加的一个 UIView。

enter image description here

我有这个代码。
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];
}

最佳答案

您应该为所有 View 应用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];
}

关于ios - 制作一些可拖动的 UIView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23966359/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com