创建一个可任意拖放的控件

看到有个app上面有个浮动的可以随意拖动的漂浮控件

想了下可以用UIButton, button设置要显示的图片, 然后通过UIPanGestureRecognizer来实现调整位置

上代码:

- (void)viewDidLoad {
    [super viewDidLoad];
    
    //初始化button
    _button = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 100, 100)];
    _button.backgroundColor     = [UIColor redColor];
    _button.layer.cornerRadius  = 50;
    _button.layer.masksToBounds = YES;
    _button.center              = self.view.center;
    
    [self.view addSubview:_button];
    
    UIPanGestureRecognizer *panGesture = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(handlePanGesture:)];
    [self.button addGestureRecognizer:panGesture];
}

- (void)handlePanGesture: (UIPanGestureRecognizer *)recognizer {
    
    CGPoint translation    = [recognizer translationInView:self.view];
    recognizer.view.center = CGPointMake(recognizer.view.center.x + translation.x,
                                         recognizer.view.center.y + translation.y);
    [recognizer setTranslation:CGPointMake(0, 0) inView:self.view];
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容