123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102 |
- //
- // 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
|