做为老司机的你们有没有遇到过这样的需求?每个商品或者商家的物品都有个星级或者其他评分,大概像以下的效果图
@ interface XWStarMaker: NSObject @ property(原子,分配)CGFloat空间; @ property(原子、强)NSString * defaultImage; @ property(原子、强)NSString * selectImage; @ property NSInteger maxValue(原子,分配); @end
<强> XWStarView.m(核心代码)强>
眼尖的同学已经看到了,XWStarView直接继承了YYLabel,熟悉YYLaebl的开发者可能知道我要干嘛了。
#进口“YYLabel.h” #进口“XWStarMaker.h” @class XWStarView; @protocol XWStarViewDelegate & lt; NSObject> @optional - (void) xw_starView: (XWStarView *) tagView明星:(NSInteger)明星; @end @ interface XWStarView: YYLabel @ property NSInteger score(原子,分配); @ property(原子、弱)id委托; - (instancetype) initWithFrame:(CGRect中)框架制造商:(空白(^)(XWStarMaker *)) makeBlock; @end
具体的实现细节看。m文件
@ interface XWStarView () @ property(原子、强)XWStarMaker *制造商; @end @ implementation XWStarView - (instancetype) initWithFrame:(CGRect中)框架制造商:(空白(^)(XWStarMaker *)) makeBlock { 如果(自我=(超级initWithFrame:帧)){ 自我。制造商=[[XWStarMaker alloc] init); 如果(makeBlock) { makeBlock (self.maker); } 自我。displaysAsynchronously=是的; 自我。fadeOnAsynchronouslyDisplay=没有; (自我creatScoreAttr); } 回归自我; } # pragma马克-私人 - (void) creatScoreAttr { NSMutableAttributedString *文本=(NSMutableAttributedString新); UIFont *字体=[UIFont systemFontOfSize: 0); for (int i=0;我& lt;self.maker.maxValue;我+ +){ 用户界面图像*图像=[界面图像imageNamed self.maker.defaultImage):; NSMutableAttributedString * attachText=[NSMutableAttributedString yy_attachmentStringWithContent:图像内容模式:UIViewContentModeLeft attachmentSize: CGSizeMake (image.size。宽度+ self.maker。空间,image.size.height) alignToFont:字体对齐:YYTextVerticalAlignmentCenter];//添加点击事件 __weak typeof(和*自我)weakSelf=自我; [attachText yy_setTextHighlightRange: NSMakeRange(0,1)颜色:nil写成backgroundColor: nil tapAction: ^ (UIView * containerView NSAttributedString *文本,NSRange范围,CGRect中矩形){ 如果(weakSelf.delegate,,[weakSelf.delegate respondstoselectorismemberofclass: @ selector (xw_starView:明星:)]){ [weakSelf.delegate xw_starView: weakSelf明星:我); } }); (文本appendAttributedString: attachText); } 自我。attributedText=文本; } 得分- (void) setScore: (NSInteger) { 如果得分(_score==) { 返回; } _score=分数;//获取图片资源 NSArray *附件=self.textLayout.attachments; for (int i=0;我& lt;attachments.count;我+ +){ YYTextAttachment *附件=附件[我]; 附件。内容=[界面图像imageNamed:我& lt;=_score & # 63;self.maker。selectImage self.maker.defaultImage):; } } @end
只要你是个iOS程序员大概都看得懂代码吧。实现很简单,但是效果却不一般,特别在复杂列表使用的时候很明显。