今天遇到一个问题就是要写一个评分视图,效果下图,主要的思路就是越界隐藏

直接上代码
- SHStarView.h
#import "SHView.h"
NS_ASSUME_NONNULL_BEGIN
@interface SHStarView : SHView
@property (nonatomic , assign) float value;//设置评分(0.0~5.0)
@property (nonatomic , assign) BOOL isEdit;//编辑,默认No
@end
NS_ASSUME_NONNULL_END
- SHStarView.m
#import "SHStarView.h"
@interface SHStarView ()
@property (nonatomic , strong) NSView *unSelectView;//未选中区域
@property (nonatomic , strong) NSView *selectView;//选中区域
@end
@implementation SHStarView
- (instancetype)initWithFrame:(NSRect)frame
{
self = [super initWithFrame:frame];
if (self) {
self.unSelectView.frame = self.bounds;
self.selectView.frame = self.bounds;
}
return self;
}
- (void)setValue:(float)value
{
_value = value;
self.selectView.frame = NSMakeRect(0, 0, value*0.2*self.bounds.size.width, self.bounds.size.height);
}
#pragma mark - 监听鼠标
- (void)mouseDown:(NSEvent *)event
{
if (self.isEdit == YES) {
CGFloat width = event.locationInWindow.x-self.frame.origin.x;
self.selectView.frame = NSMakeRect(0, 0, width, self.bounds.size.height);
self.value = width/self.bounds.size.width*5;
}
}
- (void)mouseDragged:(NSEvent *)event
{
if (self.isEdit == YES) {
CGFloat width = event.locationInWindow.x-self.frame.origin.x;
self.selectView.frame = NSMakeRect(0, 0, width, self.bounds.size.height);
self.value = width/self.bounds.size.width*5;
}
}
#pragma mark - lazy -
- (NSView *)unSelectView
{
if (!_unSelectView) {
_unSelectView = [[NSView alloc] initWithFrame:self.bounds];
[self addStarWithView:_unSelectView ImageName:@"starIcon"];
[self addSubview:_unSelectView];
}
return _unSelectView;
}
- (NSView *)selectView
{
if (!_selectView) {
_selectView = [[NSView alloc] initWithFrame:self.bounds];
[self addStarWithView:_selectView ImageName:@"starSelect"];
[self addSubview:_selectView positioned:NSWindowAbove relativeTo:self.unSelectView];
}
return _selectView;
}
#pragma mark - customMethod -
- (void)addStarWithView:(NSView *)containerView ImageName:(NSString *)imageName
{
for (NSInteger i = 0; i < 5; i++) {
CGFloat width = ceilf(self.bounds.size.width*0.2);
NSImageView *imageView = [NSImageView imageViewWithImage:[NSImage imageNamed:imageName]];
imageView.frame = NSMakeRect(width*i, 0, width, self.bounds.size.height);
[containerView addSubview:imageView];
}
}
@end
功能比较简单,就不多讲解了,有什么疑问小伙伴们可以在留言区留言
网友评论