iOS自定义控件教程(三)UIView动画入门

上一篇文章我们介绍了UIView的触摸响应链原理,顺便学习UIView的基本属性和方法。在iOS自定义控件教程(二)关于响应链的那些事中我们讲解了触摸原理,但并未具体实现其功能,接下来我们具体讲讲点击效果的实现和响应的动画效果的实现。
最终实现的效果:Github下载源码

触摸响应链UIResponder

UIView继承自UIResponder(响应链类),继承了相应的响应链方法:

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(nullable UIEvent *)event;
- (void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(nullable UIEvent *)event;
- (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(nullable UIEvent *)event;
- (void)touchesCancelled:(nullable NSSet<UITouch *> *)touches withEvent:(nullable UIEvent *)event;
- (void)touchesEstimatedPropertiesUpdated:(NSSet * _Nonnull)touches NS_AVAILABLE_IOS(9_1);

// Generally, all responders which do custom press handling should override all four of these methods.
// Your responder will receive either pressesEnded:withEvent or pressesCancelled:withEvent: for each
// press it is handling (those presses it received in pressesBegan:withEvent:).
// pressesChanged:withEvent: will be invoked for presses that provide an analog value
// (like thumbsticks or analog push buttons)
// *** You must handle cancelled presses to ensure correct behavior in your application.  Failure to
// do so is very likely to lead to incorrect behavior or crashes.
- (void)pressesBegan:(NSSet<UIPress *> *)presses withEvent:(nullable UIPressesEvent *)event NS_AVAILABLE_IOS(9_0);
- (void)pressesChanged:(NSSet<UIPress *> *)presses withEvent:(nullable UIPressesEvent *)event NS_AVAILABLE_IOS(9_0);
- (void)pressesEnded:(NSSet<UIPress *> *)presses withEvent:(nullable UIPressesEvent *)event NS_AVAILABLE_IOS(9_0);
- (void)pressesCancelled:(NSSet<UIPress *> *)presses withEvent:(nullable UIPressesEvent *)event NS_AVAILABLE_IOS(9_0);

- (void)motionBegan:(UIEventSubtype)motion withEvent:(nullable UIEvent *)event NS_AVAILABLE_IOS(3_0);
- (void)motionEnded:(UIEventSubtype)motion withEvent:(nullable UIEvent *)event NS_AVAILABLE_IOS(3_0);
- (void)motionCancelled:(UIEventSubtype)motion withEvent:(nullable UIEvent *)event NS_AVAILABLE_IOS(3_0);

其中touches开头的方法是触摸事件相关的方法;presses开头的方法,是iOS9加入的给iPhone6s等支持Deep Press功能的设备使用的相关方法;motion开头的则是给设备的陀螺仪和加速传感器使用的方法,用于获取晃动等事件。

细心的朋友可能会发现,UIViewController(后面简称VC) 和 UIView 同样继承自UIResponder,这样是为了方便UIViewController 处理他的view属性的响应事件,我们也就不用继承UIView重写他的响应链来处理VCView的响应链了,VCView默认将响应链穿给自己的VC,在VC中处理就可以了。

《iOS自定义控件教程(三)UIView动画入门》

触摸事件

触摸事件可以通过触摸链响应,也可以使用UIGesture(手势类)来响应。今天我们的例子中用了比较原始的响应链方式。

XXXSegmentView.m

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [super touchesBegan:touches withEvent:event];
}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
    [super touchesEnded:touches withEvent:event];
    
    UITouch* touch = [touches anyObject];
    CGPoint point = [touch locationInView:self];
    NSInteger detla = self.frame.size.width / self.number;
    NSInteger touchNumber = point.x / detla;
    self.selected = touchNumber;
//    [self setNeedsLayout];
    [self setSelectItemAtIndex:touchNumber animate:YES];
}

解释 touchesBegan是手指按下事件的方法,这里按下我们不做响应,单写了super方法调用父类方法,还是那句话,父类方法可能是空的不需要调用,单这是一个好习惯,可以避免一些因为继承类不调用父类方法造成的BUG。

touchesEnded是手指抬起事件的方法,首先touches这个集合中的UITouch对象,对应的就是触摸的手指。我们用anyObject取出其中之一,用locationInView:方法获取触摸点的位置。这个CGPoint是一个C中的结构体类型,只有x,y两个属性表示位置。

接下来我们根据Label的数量(self.number)来计算每个label的间隔,用总宽度除以个数。

NSInteger detla = self.frame.size.width / self.number;

接下来计算我们触摸的位置,在第几个区域

NSInteger touchNumber = point.x / detla;

这个touchNumber便是我们触摸的按钮的index。

接下来我们调用setSelectItemAtIndex方法来响应触摸这个Label的事件

- (void)setSelectItemAtIndex:(NSUInteger)idx animate:(BOOL)animated
{
    self.idx = idx;
    [self.subviews enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
        if ([obj isKindOfClass:[UILabel class]]) {
            UILabel* label = obj;
            if (self.selected + 981 == label.tag) {
                label.textColor = self.tintColor;
            }
            else
            {
                label.textColor = self.baseColor;
            }

        }
    }];
    
//这里是我们下方的那根线,移动的动画,下面详细说
    [UIView animateWithDuration:0.2 animations:^{
        UILabel* label = (UILabel*)[self viewWithTag:idx + 981];
        [self.selectView setFrame:CGRectMake(label.frame.origin.x - self.leftAndRightLineEdge, label.frame.size.height + label.frame.origin.y   + 10, label.frame.size.width + self.leftAndRightLineEdge*2, 2)];
    }];
}

解释 每一次触摸,我们都需要遍历所有的Label,将选中的,也就是self.selected + 981 == label.tag的Label改变他的颜色。

UIView动画基础

我们在上面代码中,调用self.selectView这个属性,是这么定义的

@interface

@property (nonatomic, strong) UIView* selectView;

@implementation

- (UIView *)selectView
{
    if (!_selectView) {
        _selectView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 100, 2)];
        [self addSubview:_selectView];
        _selectView.backgroundColor = self.tintColor;
    }
    return _selectView;
}

这个View在第一次调用self.selectView的时候会初始化,第二次调用时候,_selectView已经初始化过了,就不会再执行初始化方法了。

注意,关于getter和setter的内容,我们就不细说了,新手只要知道,当前的版本的编译器,自动为@property添加了@synthesize(合成)语句,所以iOS6以后,代码中很少见到

@synthesize selectView = _selectView;

这样的写法了,因为编译器自动帮你做了。所以_selectView是内部变量,单不要直接这样调用,而应该在除了- (UIView *)selectView这个getter方法外的地方,使用self.selectView来调用。

我们再来看看上面触摸代码中的动画代码:

  [UIView animateWithDuration:0.2 animations:^{
        UILabel* label = (UILabel*)[self viewWithTag:idx + 981];
        [self.selectView setFrame:CGRectMake(label.frame.origin.x - self.leftAndRightLineEdge, label.frame.size.height + label.frame.origin.y   + 10, label.frame.size.width + self.leftAndRightLineEdge*2, 2)];
    }];

解释 先使用viewWithTag:方法获取Label,注意这里返回的是UIView类,所以需要使用(UILabel*)进行强行类型转换。

UIView animateWithDuration:animations: 这个方法,是iOS4.0加入的简化版的补帧动画方法。在这个block中去改变一个UIView的frame,系统则会根据传入的Duration(单位:秒),来自动完成补间动画,类似于Flash中的补间动画。

如果不在animateWithDuration中改变view的frame,view则会直接变为新的frame,则不会有中间改变的动画过程了,是不是很简单。

最后self.leftAndRightLineEdge这是一个CGFloat浮点型数值,用来控制下面线两端超出Label的长度,我们demo中第二个例子中这个数值为20。

这样,我们的最终效果就完成。

《iOS自定义控件教程(三)UIView动画入门》

下一篇教程,我们将着手分析UIView控件响应事件并传递给其他VC或View的具体实现方法,有什么疑问请在下方留言。

    原文作者:秋刀生鱼片
    原文地址: https://segmentfault.com/a/1190000004250234
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞