簡述
在仿寫豆瓣的時候,發現了根據評分不同,星級數也不同的星級條。
百度一搜,發現Android有自帶控件UIRatingBar,而iOS得要自己寫…好吧,那就寫吧。
圖片素材
首先,要準備三張圖片,圖片如下:
空星,半星,全星
因為我們可以看到,在豆瓣的評分星級條里,只有空、半、全星,所以只需要準備這3種圖片。
思路
豆瓣的星級條中既有圖片,又有文字,所以我們自定義一個繼承于UIView的starView。
初始化方法
因為星級條要根據評分的數據來決定星的顆數,所以我們要重新創建一個初始化方法:
//在starView.m中寫 - (instancetype)initWithFrame:(CGRect)frame score:(double)score; //在starView.h中對其進行操作實現 - (instancetype)initWithFrame:(CGRect)frame score:(double)score{ self = [super initWithFrame:frame]; //記得把傳過來的score賦值給全局變量_starScore _starScore = score; return self; }
這樣,我們就可以在ViewController.m中利用此方法初始化一個星級條視圖:
starView *star = [[CJTStarView alloc] initWithFrame:CGRectMake(100, 100, 200, 50) score:6.8];
此處的score可以改成根據網絡請求得到的評分數據。
根據添加星星圖片
在這里,我設置的分數與星星的對應關系如下:
4.6-5.5 2.5顆星
5.6-6.5 3顆星
6.6-7.5 3.5顆星
7.6-8.5 4顆星
8.6-9.5 4.5顆星
而因為我們只有5顆星,所以對分數做如下處理:
_starScore = (_starScore / 2 - 0.3);
接下來就是用循環添加圖片到view上,因為我們有三種圖片,所以在循環中還要加判斷,代碼如下:
for (int count = 0; count < 5; count++) { UIImageView *starImageView = [[UIImageView alloc] init]; starImageView.frame = CGRectMake(count * self.frame.size.height, 0, self.frame.size.height, self.frame.size.height); [self addSubview:starImageView]; if (count <= _starScore - 0.5) { starImageView.image = [UIImage imageNamed:@"stars_full"]; } else { if (_starScore - count >= 0 && _starScore - count < 0.5) { starImageView.image = [UIImage imageNamed:@"stars_half"]; } else { starImageView.image = [UIImage imageNamed:@"stars_empty"]; } } }
這里的判斷條件是數學問題,就不詳細講了。
當然,如果分數與星星的對應規則和我不同,那么就要適當修正這里的判斷條件。
在星級條后添加分數
在豆瓣到星級條后面還有分數,因此我們在view中添加一個UILabel對象。
UILabel *scoreLabel = [[UILabel alloc] init]; scoreLabel.frame = CGRectMake( 5 * self.frame.size.height + 10, 8, self.frame.size.width - 5 * self.frame.size.height - 10, self.frame.size.height - 8); scoreLabel.text = [NSString stringWithFormat:@"%.1f", _starScore]; scoreLabel.textColor = [UIColor grayColor]; scoreLabel.font = [UIFont systemFontOfSize:25];
這里要注意,因為我們在設置星級圖的時候會修改_starScore的值,所以要在添加星星圖片之前設置UILabel。
效果圖
最后做出來到效果如下:
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持億速云。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。