1.定义一个 Label 属性
@property (strong, nonatomic) UILabel *simple;
2.在 viewDidLoad里面实现一下
- (void)viewDidLoad {
[super viewDidLoad];
测试控制器是否响应 (改变下颜色看看工程是否调通)
self.view.backgroundColor = [UIColor redColor];
1.设置 Label 的 frame
self.simple = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 100, 100)];
2. 修改中心点
self.simple.center = self.view.center;
3.
设置颜色
self.simple.backgroundColor = [UIColor magentaColor];
4.
设置圆角
self.simple.layer.cornerRadius = 20;
self.simple.clipsToBounds
= YES;
5. 添加到视图上
[self.view addSubview:self.simple];
}
// 开始触摸
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
#define KColor arc4random()% 256 / 255.0
#define Kwidth self.view.bounds.size.width
#define Khight self.view.bounds.size.height
#define Kmax 300
#define Kmin 30
1. 设置随即大小
CGFloat side = arc4random()% (Kmax - Kmin + 1) + Kmin;
self.simple.layer.cornerRadius = side / 2;
self.simple.clipsToBounds = YES;
CGFloat x = arc4random() % (NSInteger)(Kwidth - 50 + 1) + 50;
CGFloat y = arc4random() % (NSInteger)(Khight - 50 + 1) + 50;
2.
修改中心点
self.simple.center = CGPointMake(x, y);
3.
设置随机色
self.simple.backgroundColor = [UIColor colorWithRed:KColor green:KColor blue:KColor alpha:1];
NSLog(@"我开始摸了");
}
移动触摸
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
self.simple.backgroundColor = [UIColor colorWithRed:KColor green:KColor blue:KColor alpha:1];
1.
获取触摸的对象 取出来的对象就是 UITouch 类型的
UITouch *touth = [touches anyObject];
2.
获取前一个点
CGPoint p1 = [touth preciseLocationInView:self.view];
3.
获取当前点
CGPoint p2 = [touth locationInView:self.view];
4.
根据两个点的横纵向间距来计算出移动结果,并复制给 center,更新位置(改变中心点的位置来达到移动的效果)
self.view.center = CGPointMake(self.view.center.x + p2.x - p1.x, self.view.center.y + p2.y - p1.y);
5.
直接找p2这个点
self.simple.center = CGPointMake(p1.x, p1.y);
}
结束触摸
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
NSLog(@"不摸了~~");
}
// 取消触摸
- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event
{
NSLog(@"取消触摸");
}
@property (strong, nonatomic) UILabel *simple;
2.在 viewDidLoad里面实现一下
- (void)viewDidLoad {
1.设置 Label 的 frame
2.
3.
4.
5.
}
// 开始触摸
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
#define KColor arc4random()% 256 / 255.0
#define Kwidth self.view.bounds.size.width
#define Khight self.view.bounds.size.height
#define Kmax 300
#define Kmin 30
1.
2.
3.
}
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
1.
2.
3.
4.
5.
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
}
// 取消触摸
- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event
{
}