I.触摸
//Touch有以下四种响应方式,若注掉其中一个,此动作将无法再响应(如果可能,会在其父视图中寻求响应)
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
NSLog(@"触摸开始");
}
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
NSLog(@"触摸过程");
}
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
NSLog(@"触摸结束");
}
- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event
{
NSLog(@"触摸中止");
}
// 随机颜色的生成
NSInteger r = arc4random() % 255;
NSInteger g = arc4random() % 255;
NSInteger b = arc4random() % 255;
UIColor *color = [UIColor colorWithRed:r / 255. green:g / 255. blue:b / 255. alpha:1.0];
self.backgroundColor = color;
// 实现将一个UIView跟随手指的触点移动的功能,在touchesBegan中,获取到手指触点,获得其与UIView坐标的差值(为了解决拖动 UIView时,模块跳动的问题),此差值作为一个全局变量,会在touchesMoved中得到体现,即通过触点拖动UIView前,会减去此差值,然 后再实现接下来的动作
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *touch = [touches anyObject];
// 获取手指触摸屏幕的第一个点
CGPoint firstPoint = [touch locationInView:self.window];
_x = self.frame.origin.x - firstPoint.x;
_y = self.frame.origin.y - firstPoint.y;
}
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
// 取出当前屏幕上手指触摸的点的信息
UITouch *touch = [touches anyObject];
// 2. 根据一个视图,获取当前触摸的点
CGPoint currentPoint = [touch locationInView:self.window];
currentPoint.x += _x;
currentPoint.y += _y;
NSLog(@"%@", NSStringFromCGPoint(currentPoint));
// 3. 将当前点赋值到当前视图上
CGRect frame = self.frame;
frame.origin = currentPoint;
self.frame = frame;
}
II.响应链
AView *aView = [[[AView alloc] initWithFrame:CGRectMake(50, 50, 200, 200)] autorelease];userInteractionEnabled:响应查找时(从window开始向下级查找),如若关闭,则无法继续向下查找。
aView.backgroundColor = [UIColor redColor];
aView.userInteractionEnabled = NO;
[self addSubview:aView];
BView *bView = [[[BView alloc] initWithFrame:CGRectMake(0, 0, 100, 100)] autorelease];
bView.backgroundColor = [UIColor blueColor];
[aView addSubview:bView];
如以上code,点击bView,虽然bView的交互未关闭,但由于其父视图的交互关闭,故点击时由aView的父视图(rootView)来处理。
默认交互关闭的有UILabel, UIImageView,所以当我们将一个UIButton放在一个UILabel上时(即父视图是UILabel),button将无法点击。
// 一个打印此方法功能的语句
NSLog(@"%s", __FUNCTION__);