先来看看效果图
警示文本框.gif产品经理给的需求
用户点击登录按钮时,若登录栏未填写,则显示红色警示框提示用户,如上图。
封装思路
新建一个继承于UITextField
的控件AlertTextField
,在AlertTextField
上添加一个中间空、边框为红色、大小形状和AlertTextField
一样的CAShapeLayer
,重复改变其透明度实现动画效果。
开始封装
先新建一个继承于UITextField
的控件AlertTextField
为其添加一个属性
@property (nonatomic,strong) CAShapeLayer *alertLayer;
创建CAShapeLayer
- (void)createAlertLayer{ // 设置layer相关属性 self.alertLayer = [CAShapeLayer layer]; // 大小和文本框一致 self.alertLayer.frame = self.bounds; // 画线 非圆角 self.alertLayer.path = [UIBezierPath bezierPathWithRoundedRect:self.alertLayer.bounds cornerRadius:0].CGPath; // 线宽 self.alertLayer.lineWidth = 6. / [[UIScreen mainScreen] scale]; // 设置为实线 self.alertLayer.lineDashPattern = nil; // 填充颜色透明色 self.alertLayer.fillColor = [UIColor clearColor].CGColor; // 边框颜色为红色 self.alertLayer.strokeColor = [UIColor redColor].CGColor;
[self.layer addSublayer:self.alertLayer];
}
设置动画
- (void)showAlert{
[self createAlertLayer];
// 透明度变化
CABasicAnimation *opacityAnimation = [CABasicAnimation animationWithKeyPath:@"opacity"];
opacityAnimation.fromValue = [NSNumber numberWithFloat:1.0];
opacityAnimation.toValue = [NSNumber numberWithFloat:0.0];
opacityAnimation.repeatCount = 5;
opacityAnimation.repeatDuration = 2;
opacityAnimation.autoreverses = YES;
[self.alertLayer addAnimation:opacityAnimation forKey:@"opacity"];
// 2秒后移除动画
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
// 2秒后异步执行这里的代码...
// 移除动画
[self.alertLayer removeFromSuperlayer];
});
}
开始使用
- (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib.
// 创建一个AlertTextField
AlertTextField *textField = [[AlertTextField alloc]initWithFrame:CGRectMake(30, 50, 200, 30)];
textField.placeholder = @"请输入用户名";
textField.tag = 100;
[self.view addSubview:textField];
[textField becomeFirstResponder];
// 创建一个button
UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
button.frame = CGRectMake(20, 100, 100, 30);
[button setTitle:@"登录" forState:UIControlStateNormal];
[self.view addSubview:button];
[button addTarget:self action:@selector(showAlert) forControlEvents:UIControlEventTouchUpInside];
}
// 文本框警示
- (void)showAlert{ AlertTextField *textField = [self.view viewWithTag:100]; [textField showAlert]; }
总结
CALayer和贝塞尔曲线对于建动画非常好用,建议还没使用过的同学去了解一下。
学习CALayer和贝塞尔曲线链接
网友评论