最近项目需要写类似货物5星评价,所以就写一下。具体的样子如下。
下面主要介绍一下主要代码
在.H文件中的公有属性和方法
// 点击星星后的Block ,返回当前视图,和当前点击的第几个星星(从1开始数)
@property (nonatomic, copy) StarEvaluateBlock starEvaluateBlock;
// 默认星星
@property (nonatomic, strong) UIImage *defaultImage;
// 亮的星星
@property (nonatomic, strong) UIImage *lightImage;
// 默认有五个星星
- (instancetype)initWithFrame:(CGRect)frame
starIndex:(NSInteger)index
starWidth:(CGFloat)starWidth
space:(CGFloat)space
defaultImage:(UIImage *)defaultImage
lightImage:(UIImage *)lightImage
isCanTap:(BOOL)isCanTap;
下面是.m
// 默认有五个星星
- (instancetype)initWithFrame:(CGRect)frame
starIndex:(NSInteger)index
starWidth:(CGFloat)starWidth
space:(CGFloat)space
defaultImage:(UIImage *)defaultImage
lightImage:(UIImage *)lightImage
isCanTap:(BOOL)isCanTap{
self = [super initWithFrame:frame];
if (self) {
if (defaultImage) {
self.defaultImage = defaultImage;
} else {
self.defaultImage = [UIImage imageNamed:@"五星评价_灰"];
}
if (lightImage) {
self.lightImage = lightImage;
} else {
self.lightImage = [UIImage imageNamed:@"五星评价_黄"];
}
for (NSInteger j = 0; j < 5; j++) {
UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake(j* (starWidth + space), 0, starWidth, self.height)];
btn.enabled = isCanTap;
btn.tag = j + 1;
[btn addTarget:self action:@selector(starTapBtn:) forControlEvents:UIControlEventTouchUpInside];
// 上左下右 星星居中
[btn setImageEdgeInsets:UIEdgeInsetsMake((self.height - starWidth)/2, 0, (self.height - starWidth)/2, 0)];
if (j < index) {
[btn setImage:self.lightImage forState:UIControlStateNormal];
} else {
[btn setImage:self.defaultImage forState:UIControlStateNormal];
}
[self addSubview:btn];
// self.width
self.width = (starWidth + space) * 5;
}
}
return self;
}
//这边的方法主要是按钮地点击的时候遍历一下按钮点击前面和点击过的按都显示为选中
- (void)starTapBtn:(UIButton *)btn{
for (NSInteger i = 1; i <= 5; i++) {
UIButton *starBtn = (UIButton *)[self viewWithTag:i];
if (i <= btn.tag) {
[starBtn setImage:self.lightImage forState:UIControlStateNormal];
} else {
[starBtn setImage:self.defaultImage forState:UIControlStateNormal];
}
}
if (self.starEvaluateBlock) {
self.starEvaluateBlock(self,btn.tag);
}
}
具体代码衔接为我只是一个demo