在开发过程中,我们经常会遇到一些增加星星好评数,等类似问题,而很多时候我们自己用for循环增加的星星数会慢慢叠加(具体可以看图层)从而拖垮程序,今天我就分享一个增加星星数的一个封装好的Demo
在.h文件里面声明两个属性
@property(nonatomic,assign) NSInteger starNumber;
@property(nonatomic,assign) CGFloat rating;
.m文件里面的
@interfaceStarView ()
@property(nonatomic,retain) UILabel *ratingLabel;
@end
@implementationStarView
- (void)dealloc
{
[_ratingLabel release];
[superdealloc];
}
- (instancetype)initWithFrame:(CGRect)frame
{
self= [superinitWithFrame:frame];
if(self) {
for(NSInteger i =0; i <5; i++) {
UIImageView *imageView = [[UIImageView alloc] init];
imageView.image = [UIImage imageNamed:@"l_star_white.png"];
[selfaddSubview:imageView];
[imageView release];
}
self.ratingLabel = [[UILabel alloc] init];
self.ratingLabel.textColor = [UIColor orangeColor];
self.ratingLabel.textAlignment = NSTextAlignmentRight;
self.ratingLabel.font = [UIFont systemFontOfSize:14];
[selfaddSubview:self.ratingLabel];
[_ratingLabel release];
}
returnself;
}
- (void)setStarNumber:(NSInteger)starNumber
{
_starNumber = starNumber;
[selfresetFrame];
}
- (void)resetFrame
{
CGFloat width =self.bounds.size.width /7;
CGFloat height =self.bounds.size.height;
//满星的个数
NSInteger fullStars =self.starNumber /10;
BOOLhalfStar = ((self.starNumber %10) ==5)?YES:NO;
for(NSInteger i =0; i <5; i++) {
UIImageView *imageView = [self.subviews objectAtIndex:i];
imageView.frame = CGRectMake(width * i, (height - width) /2, width, width);
if(i < fullStars) {
imageView.image = [UIImage imageNamed:@"l_star_red.png"];
}elseif(halfStar ==YES&& i == fullStars) {
imageView.image = [UIImage imageNamed:@"l_star_half.png"];
}else{
imageView.image = [UIImage imageNamed:@"l_star_white.png"];
}
}
}
- (void)setRating:(CGFloat)rating
{
_rating = rating;
self.ratingLabel.frame =self.bounds;
self.ratingLabel.text = [NSString stringWithFormat:@"%.1f", _rating];
}