ios 编写UIControl子类

来源:互联网 发布:c语言cout 编辑:程序博客网 时间:2024/05/29 14:09

构建UIControl的过程一般分成四部。首先继承UIControl,创建新的自定义类,然后在新类中初始化方法中安排好控件的样貌。接下来编写一些方法,以便追踪并拦截触摸事件,最后产生相关事件及视觉反馈效果。

UIControl实例有一套应对触摸事件的方法

beginTrackingWithTouch:withEvent:-->如果在控件的范围内发生触摸事件就会调用这个方法。

continueTrackingWithTouch:withEvent:-->如果触摸事件还在控件范围内持续,就会反复调用这个方法。

endTrackingWithTouch:withEvent:-->在处理事件结束前的最后一次触摸。

cancelTrackingWithEvent:-->触摸取消的情况下调用。

调用sendActionsForControlEvents:方法为自定义控件添加事件派发功能。这个方法可以把某个事件发送给控件的目标,控件通过向UIApplication单例发消息来实现这一操作的。UIApplication对象是所有消息的集中派发点。无论控件类对么简单,开发者都应该尽量多支持一些事件类型,因为你无法准确预料这个类在将来的用途,把事件类型提供完备一些可以使控件以后用起来更加灵活。

下面就是一个简单的例子:


关键代码如下:

- (void)updateColorFromTouch:(UITouch *)touch{    CGPoint touchPoint = [touch locationInView:self];    float hue = touchPoint.x / self.frame.size.width;    float saturation = touchPoint.y / self.frame.size.height;    self.backgroundColor = [UIColor colorWithHue:hue saturation:saturation brightness:1 alpha:1];    [self sendActionsForControlEvents:UIControlEventValueChanged];    }- (BOOL)beginTrackingWithTouch:(UITouch *)touch withEvent:(UIEvent *)event{    [self updateColorFromTouch:touch];    [self sendActionsForControlEvents:UIControlEventTouchDown];    return YES;}- (BOOL)continueTrackingWithTouch:(UITouch *)touch withEvent:(UIEvent *)event{    CGPoint touchPoint = [touch locationInView:self];    if (CGRectContainsPoint(self.frame, touchPoint)) {        [self updateColorFromTouch:touch];        [self sendActionsForControlEvents:UIControlEventTouchDragInside];    }else{        [self sendActionsForControlEvents:UIControlEventTouchDragOutside];    }    return YES;}- (void)endTrackingWithTouch:(UITouch *)touch withEvent:(UIEvent *)event{    CGPoint touchPoint = [touch locationInView:self];    if (CGRectContainsPoint(self.frame, touchPoint)) {        [self updateColorFromTouch:touch];        [self sendActionsForControlEvents:UIControlEventTouchUpInside];    }else{        [self sendActionsForControlEvents:UIControlEventTouchUpOutside];    }}- (void)cancelTrackingWithEvent:(UIEvent *)event{    [self sendActionsForControlEvents:UIControlEventTouchCancel];}

这里就是通过触摸事件方法实现的简单的颜色选择器


0 0