iOS开发小笔记 | 封装一个星级view(基于masonry)

就是这么一种常见自定义控件:

5星好评

3颗星半

思路:

  • 自定义一个StarView
  • 先依次放5个灰色星
  • 再放一个view(裁剪view),作为5颗黄色星的父view
  • 在裁剪view上依次放5颗黄色星
  • 根据传入的值,改变裁剪view的宽,完成星级展示

参考代码:

  • .h文件
/** 快递员星级 */
@property (nonatomic,assign) CGFloat star;
  • .m文件
@interface StarView (){
    /** 5颗黄色星的父view,用来裁剪5颗黄色星 */
    UIView *_clipView;
}

@end

@implementation StarView

#pragma mark - 构造方法
- (instancetype)initWithFrame:(CGRect)frame{
    if (self = [super initWithFrame:frame]) {
        // UI搭建
        [self setUpUI];
    }
    return self;
}

#pragma mark - UI搭建
/** UI搭建 */
- (void)setUpUI{
    // 创建下面的5个灰色星星
    UIView *lastView = nil;
    for (int i = 0; i < 5; i ++) {
        UIImageView *grayImageView = [[UIImageView alloc]init];
        [self addSubview:grayImageView];
        grayImageView.image = [UIImage imageNamed:@"non_star"];
        [grayImageView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(self);
            make.bottom.mas_equalTo(self);
            make.width.mas_offset(14);
            //make.right.mas_equalTo(grayImageView.mas_left).mas_offset(14);
            if (lastView) {
                make.left.mas_equalTo(lastView.mas_right);
            }else{
                make.left.mas_equalTo(self);
            }
        }];
        lastView = grayImageView;
    }
    
    [self mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(lastView);
    }];
    
    // 裁剪黄色星的view
    _clipView = [[UIView alloc]init];
    [self addSubview:_clipView];
    _clipView.clipsToBounds = YES; // 裁剪开启
    [_clipView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self);
        make.left.mas_equalTo(self);
        make.bottom.mas_equalTo(self);
        make.width.mas_equalTo(self).multipliedBy(1);
    }];

    // 创建5个黄色星
    UIView *lastYellowView = nil;
    for (int i = 0; i < 5; i ++) {
        UIImageView *yellowImageView = [[UIImageView alloc]init];;
        [_clipView addSubview:yellowImageView];
        yellowImageView.image = [UIImage imageNamed:@"full_star"];
        [yellowImageView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(self);
            make.bottom.mas_equalTo(self);
            make.width.mas_equalTo(14);
            if (lastYellowView) {
                make.left.mas_equalTo(lastYellowView.mas_right);
            }else{
                make.left.mas_equalTo(self);
            }
        }];
        lastYellowView = yellowImageView;
    }
}

#pragma - 设置星级
/** 设置星级 */
- (void)setStar:(CGFloat)star{
    _star = star;
    // 计算黄星所占百分比
    CGFloat percentage = _star / 5.0;
    CGFloat offset = (1 - percentage) * (14 * 5);
    [_clipView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo(self.mas_width).mas_offset(-offset);
    }];
}

你可能感兴趣的:(iOS开发小笔记 | 封装一个星级view(基于masonry))