美文网首页程序员
Touch和自定义视图

Touch和自定义视图

作者: 每日总结 | 来源:发表于2016-03-17 22:37 被阅读60次

自定义视图

苹果公司给我们提供了很多的类,但有时我们仍然感到不够用,这时我们就需要封装自己的自定义视图,将功能分成不同的自定义视图类来编写;
比如一个条形视图上添加一个UILabel一个UITextField等等;

Touch

实现touch方法不需要遵守协议也不用创建touch对象,直接调用方法即可,touch方法在UIResponder中;

- (void)touchesBegin:(NSSet <UITouch *> *)touches withEvent:(UIEvent *)event{
    NSLog(@"开始触摸");
}// 开始触摸一般是我们调用最多的方法;
- (void)touchesEnded:(NSSet <UITouch *> *)touches withEvent:(UIEvent *)event{
    NSLog(@"结束触摸");
}
- (void)touchesMoved:(NSSet <UITouch *> *)touches withEvent:(UIEvent *)event{
    NSLog(@"移动触摸");
}// 移动触摸方法在触摸移动过程中会不断被触发;
- (void)touchesCancelled:(NSSet <UITouch *> *)touches withEvent:(UIEvent *)event{
    NSLog(@"取消触摸");
}// 取消触摸是指在触摸的过程中发生各种中断触摸的事件,如:电话,弹窗等;

touch的相关应用

- (void)touchesBegin:(NSSet <UITouch *> *)touches withEvent:(UIEvent *)event{
    // 获取手指位置
    UITouch *touch = [touches anyObject];// 通过正则算法取手指位置
    // 将位置转化为点
    CGPoint point = [touch locationInView:self];
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(point.x,point.y,5,5)];
    view.backgroundColor = [UIColor redColor];
    [self addSubview:view];    
}

- (void)touchesMoved:(NSSet <UITouch *> *)touches withEvent:(UIEvent *)event{
    UITouch *touch = [touches anyObject];
    // 获取当前位置
    CGPoint end = [touch locationInView:self];
    // 获取前一时刻位置
    CGPoint start = [touch previousLocationInView:self];
    // 每次触发时这次的当前位置都会变成下次的前一时刻位置
    CGFloat spaceX = end.x - start.x;
    CGFloat spaceY = end.y - start.y;
    // 让视图跟随触摸移动
    self.center = CGPointMake(self.center.x + spaceX,self.center.y + spaceY );
}

Touch和手势
手势相当于是对Touch的加强,Touch在应用上比较简单,但在对于一些复杂的操作时,就显得有些不足,而手势在使用前需要为其开辟空间,进行初始化,但功能上比Touch要强;

相关文章

网友评论

    本文标题:Touch和自定义视图

    本文链接:https://www.haomeiwen.com/subject/imktlttx.html