// // TCPageIndicator.m // MyMacDevDemo // // Created by tangchao on 2021/12/11. // #import "TCPageIndicator.h" @interface TCPageIndicator () {} @property (nonatomic, strong) NSMutableArray *indicatorRects; @end @implementation TCPageIndicator - (instancetype)initWithFrame:(NSRect)frameRect { if (self = [super initWithFrame:frameRect]) { self.selectedColor = [NSColor grayColor]; self.normalColor = [[NSColor grayColor] colorWithAlphaComponent:0.5]; self.indicatorMargin = 8.f; self.currentPage = 0; self.numberOfPages = 0; self.pageIndicatorSize = CGSizeMake(6, 6); self.enabled = YES; self.indicatorRects = [NSMutableArray arrayWithCapacity:4]; } return self; } - (void)setIndicatorMargin:(CGFloat)indicatorMargin { _indicatorMargin = indicatorMargin; [self setNeedsDisplay:YES]; } - (void)setCurrentPage:(NSUInteger)currentPage { _currentPage = currentPage; [self setNeedsDisplay:YES]; } - (void)setNumberOfPages:(NSUInteger)numberOfPages { _numberOfPages = numberOfPages; [self setNeedsDisplay:YES]; } - (void)setPageIndicatorSize:(NSSize)pageIndicatorSize { _pageIndicatorSize = pageIndicatorSize; [self setNeedsDisplay:YES]; } - (void)drawRect:(NSRect)dirtyRect { [super drawRect:dirtyRect]; CGFloat indicatorAreaWidth = self.pageIndicatorSize.width * self.numberOfPages + self.indicatorMargin * (self.numberOfPages-1); CGFloat leftPosition = (self.bounds.size.width - indicatorAreaWidth) * 0.5; CGFloat topPadding = (self.bounds.size.height - self.pageIndicatorSize.height) * 0.5; [self.indicatorRects removeAllObjects]; for (int i = 0; i < self.numberOfPages; i++) { NSPoint position = NSMakePoint(leftPosition, topPadding); CGRect rect = CGRectMake(position.x, position.y, self.pageIndicatorSize.width, self.pageIndicatorSize.height); [self.indicatorRects addObject:[NSValue valueWithRect:rect]]; NSBezierPath *path = [NSBezierPath bezierPathWithOvalInRect:rect]; if (self.currentPage == i) { [self.selectedColor setFill]; } else { [self.normalColor setFill]; } [path fill]; leftPosition += (self.pageIndicatorSize.width + self.indicatorMargin); } } - (void)mouseDown:(NSEvent *)event { [super mouseDown:event]; if (self.enabled == NO) { return; } NSPoint eventLocation = event.locationInWindow; /// 转换成视图的本地坐标 NSPoint pointInView = [self convertPoint:eventLocation fromView:nil]; for (int i = 0; i < self.numberOfPages; i++) { NSRect rect = CGRectInset([self.indicatorRects[i] CGRectValue], -2, -2); if (NSPointInRect(pointInView, rect)) { self.currentPage = i; } } } @end