- (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom]; btn.frame = CGRectMake(100, 100, 50, 50); btn.backgroundColor = [UIColor yellowColor]; btn.clipsToBounds = YES; btn.layer.cornerRadius = 25; btn.tag = 10086; [self.view addSubview:btn]; //添加手势 //添加移动的手势 UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc]initWithTarget:self action:@selector(locationChange:)]; pan.delaysTouchesBegan = YES; [btn addGestureRecognizer:pan]; } - (void)locationChange:(UIPanGestureRecognizer *)recognizer { CGPoint translation = [recognizer translationInView:self.view]; CGFloat centerX=recognizer.view.center.x+ translation.x; CGFloat thecenter=0; recognizer.view.center=CGPointMake(centerX, recognizer.view.center.y+ translation.y); [recognizer setTranslation:CGPointZero inView:self.view]; if(recognizer.state==UIGestureRecognizerStateEnded|| recognizer.state==UIGestureRecognizerStateCancelled) { if(centerX>ScreenWidth/2) { thecenter=ScreenWidth-50; }else{ thecenter=50; } [UIView animateWithDuration:0.3 animations:^{ recognizer.view.center=CGPointMake(thecenter, recognizer.view.center.y+ translation.y); }]; } }