电商封装iOS开发实用技术

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

2017-03-17  本文已影响298人  无夜之星辰

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

5星好评
3颗星半

思路:

参考代码:

/** 快递员星级 */
@property (nonatomic,assign) CGFloat star;
@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);
    }];
}
上一篇 下一篇

猜你喜欢

热点阅读