IOS可以拖动的UIButton

来源:互联网 发布:智联招聘java 编辑:程序博客网 时间:2024/05/01 21:52

http://blog.csdn.net/qq5306546/article/details/8083402

当点击Button后,拖动到屏幕上的其它位置,Button会根据移动的方法位置发生变化

[cpp] view plain copy
  1. #import "ViewController.h"  
  2.   
  3. @interface ViewController ()  
  4.   
  5. @property (nonatomic, strong) UIButton *btn;  
  6.   
  7. @end  
  8.   
  9. @implementation ViewController  
  10. @synthesize btn;  
  11.   
  12. - (void)viewDidLoad  
  13. {  
  14.     [super viewDidLoad];  
  15.     self.btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];  
  16.     self.btn.frame = CGRectMake(10, 10, 50, 50);  
  17.   
  18.     [self.btn setTitle:@"触摸" forState:UIControlStateNormal];  
  19.     [self.btn setTitle:@"移动" forState:UIControlEventTouchDown];  
  20.     [self.btn addTarget:self action:@selector(dragMoving:withEvent: )forControlEvents: UIControlEventTouchDragInside];  
  21.     [self.btn addTarget:self action:@selector(dragEnded:withEvent: )forControlEvents: UIControlEventTouchUpInside |  
  22.      UIControlEventTouchUpOutside];  
  23.       
  24.     [self.view addSubview:self.btn];  
  25. }  
  26.   
  27.   
  28. - (void) dragMoving: (UIControl *) c withEvent:ev  
  29. {  
  30.     c.center = [[[ev allTouches] anyObject] locationInView:self.view];  
  31. }  
  32.   
  33. - (void) dragEnded: (UIControl *) c withEvent:ev  
  34. {  
  35.     c.center = [[[ev allTouches] anyObject] locationInView:self.view];  
  36. }  
  37.   
  38. @end  


0 0
原创粉丝点击