UIViewController中初始化方法,loadView,viewdidLoad只会运行一次,但是ViewAppear只要视图显示,就会运行一次
事件三种:触摸_摇一摇_遥控器
定义一个myTextField属性并进行创建
self.myTextField=[[UITextField alloc]initWithFrame:CGRectMake(100, 500, 150, 40)];
self.myTextField.layer.borderWidth=1;
self.myTextField.layer.cornerRadius=10;
[self.view addSubview:self.myTextField];
[_myTextField release];
触摸
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
NSLog(@"触摸开始");
[self.myTextField resignFirstResponder];
}
-(void)touchCancelled:(NSSet *)touches withEvent:(UIEvent *)event
{
NSLog(@"触摸取消");
}
-(void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event{
NSLog(@"触摸取消");
}
-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{
NSLog(@"触摸结束");
}
-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{
NSLog(@"触摸移动");
}
定义UIView属性并进行创建
UIView *view = [[UIView alloc]initWithFrame:CGRectMake(100, 100, 200, 200)];
[self.view addSubview:view];
view.backgroundColor=[UIColor redColor];
[view release];
摇一摇
-(void)motionBegan:(UIEventSubtype)motion withEvent:(UIEvent *)event{
NSLog(@"摇一摇开始");
//通过摇一摇更换背景颜色
self.view.backgroundColor=[UIColor colorWithRed:arc4random()%256/255.0 green:arc4random()%256/255.0 blue:arc4random()%256/255.0 alpha:1];
}
-(void)motionCancelled:(UIEventSubtype)motion withEvent:(UIEvent *)event{
NSLog(@"摇一摇被取消");
}
-(void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event{
NSLog(@"摇一摇结束");
}
定义UIButton属性并进行创建
UIButton *button1=[UIButton buttonWithType:UIButtonTypeSystem];
button1.frame=CGRectMake(0, 0, 100, 100);
button1.backgroundColor=[UIColor greenColor];
[view addSubview:button1];
[button1 addTarget:self action:@selector(click:) forControlEvents:UIControlEventTouchUpInside];
第一响应者
-(void)click:(UIButton *)button{
NSLog(@"fsafafafa");
//变成第一响应者
[self.myTextField becomeFirstResponder];
}
创建一个MyView的类,并创建一个MyView类型的对象如下
MyView *myView=[[MyView alloc]initWithFrame:CGRectMake(100, 200, 100, 100)];
myView.backgroundColor=[UIColor yellowColor];
[self.view addSubview:myView];
[myView release];
目的:让myView随我们的手指进行移动
1.在MyView.m里我们定义一个属性用来记录视图开始的坐标
@property(nonatomic,assign)CGPoint start point;
2.触摸开始设置
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
// 这是触碰这个视图让其改变其颜色背景
// self.backgroundColor=[UIColor colorWithRed:arc4random()%256/255.0 green:arc4random()%256/255.0 blue:arc4random()%256/255.0 alpha:1];
// 集合元素个数字符串lunch.字典是count数组是count
// NSLog(@"%ld",touches.count);
//正题:
//集合有一个触摸类的对象
UITouch *touch=[touches anyObject];
//通过触摸对象获取相应的视图的当前位置
self.startpoint=[touch locationInView:self];
NSLog(@"%g",self.startpoint.x);
}
3.触摸移动设置
-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
//通过移动找到变化,然后让MyView也进行相应的调整.从而实现视图随手移动的效果
//获取触摸对象
UITouch *touch=[touches anyObject];
//获取移动坐标
CGPiont movePoint=[touch locationInView:self];
//坐标变化
CGFloat dx = movePoint.x - self.startpoint.x;
CGFloat dy = movePoint.y - self.startpoint.y;
//设置视图的移动变化
self.center=CGPointMake(self.center.x+dx, self.center.y+dy);
}