iOS豆瓣评分(根据评分数显示星星数)

在开发过程中,我们经常会遇到一些增加星星好评数,等类似问题,而很多时候我们自己用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];

}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 在iOS中随处都可以看到绚丽的动画效果,实现这些动画的过程并不复杂,今天将带大家一窥ios动画全貌。在这里你可以看...
    每天刷两次牙阅读 8,585评论 6 30
  • 在iOS中随处都可以看到绚丽的动画效果,实现这些动画的过程并不复杂,今天将带大家一窥iOS动画全貌。在这里你可以看...
    F麦子阅读 5,149评论 5 13
  • 1、设置UILabel行间距 NSMutableAttributedString* attrString = [[...
    十年一品温如言1008阅读 1,741评论 0 3
  • 1、设置UILabel行间距 NSMutableAttributedString* attrString = [[...
    FF_911阅读 1,430评论 0 3
  • 没有那么多的为什么!!有的只是我爱你❤!!!在一个偏远的地方有着一个无所事事的人!!每天他都是在流浪……每天都在追...
    景诺炙热阅读 308评论 0 0