自定义文本横向渐变消失的控件

自定义文本横向渐变消失的控件

.h文件内容

#import <UIKit/UIKit.h>
@interface FadeStringView : UIView
/**
 *  输入文本
 */
@property (strong, nonatomic) NSString *text;

/**
 *  @brief  向右渐变消失
 */
- (void)fadeRight;
//最好这样子实现
- (void)fadeRightWithDuration:(NSTimeInterval)duration animated:(BOOL)animated;
@end

.m文件内容

#import "FadeStringView.h"
@interface FadeStringView ()

@property (strong, nonatomic) UILabel *label;
@property (strong, nonatomic) UIView *mask;//作为遮罩的mask

@end

@implementation FadeStringView

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        //创建label
        [self createLabel:frame];
        //创建出mask
        [self createMask:self.bounds];

    }
    return self;
}

- (void)createLabel:(CGRect)frame{
    self.label              = [[UILabel alloc] initWithFrame:frame];
    self.label.font         = [UIFont systemFontOfSize:30.f];
    self.label.textAlignment = NSTextAlignmentCenter;

    [self addSubview:self.label];
}



-(void)createMask:(CGRect)frame
{
    CAGradientLayer *gradientLayer = [CAGradientLayer layer];
    gradientLayer.frame = frame;
    gradientLayer.colors = @[(__bridge id)[UIColor clearColor].CGColor,
                             (__bridge id)[UIColor blackColor].CGColor,
                             (__bridge id)[UIColor blackColor].CGColor,
                             (__bridge id)[UIColor clearColor].CGColor];
    gradientLayer.locations = @[@(0.01),@(0.1),@(0.9),@(0.99)];
    gradientLayer.startPoint = CGPointMake(0, 0);
    gradientLayer.endPoint = CGPointMake(1, 0);

    //创建并接管mask
    self.mask = [[UIView alloc] initWithFrame:frame];

    //将渐变图层加到mask图层上作为子图层
    [self.mask.layer  addSublayer:gradientLayer];
    self.maskView = self.mask;
}

/**
 *  @brief  向右渐变消失
 */
- (void)fadeRight{

    [UIView animateWithDuration:3.f animations:^{
        CGRect frame = self.mask.frame;
        frame.origin.x += frame.size.width;
        self.mask.frame = frame;

    }];



}

/**
 *  重写setter/getter 方法
 */
@synthesize text = _text;
- (void)setText:(NSString *)text{
    _text = text;
    self.label.text = text;
}

-(NSString *)text{
    return _text;
}
@end

viewController里调用函数如下

#import "FadeStringView.h"

 FadeStringView *fadeStringView = [[FadeStringView alloc] initWithFrame:CGRectMake(0, 0, 300, 40)];
    fadeStringView.center = self.view.center;
    fadeStringView.text = @"iOS开发测试用例";
    [self.view addSubview:fadeStringView];
    [fadeStringView fadeRight];

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值