iOS开发中,因为界面要求,需要实现选项卡的功能。功能类似于UISegmentedControl。(相当于自定义了一个简易版的UISegmentedControl)
实现效果图:
主要几个关键点:
1.在特定的区域内绘制居中的文字:
/** 绘制文字*/NSMutableParagraphStyle*paragraphStyle =[[NSMutableParagraphStyle alloc] init];
paragraphStyle.alignment=NSTextAlignmentCenter;
NSAttributedString*test =[[NSAttributedString alloc] initWithString:title
attributes:@{
NSFontAttributeName:[UIFont systemFontOfSize:16],
NSParagraphStyleAttributeName:paragraphStyle,
NSForegroundColorAttributeName:hasUnderline?self.selectedColor :self.unselectedColor
}];//获取绘制区域中心点
NSInteger selectedCount =[self.titleArray count];
CGFloat lengthOfEachSelectedSpace= self.frame.size.width /selectedCount;
CGFloat horizontalStartLocation= lengthOfEachSelectedSpace *rank;
CGFloat horizontalEndLocation= lengthOfEachSelectedSpace *(rank +1);
CGFloat horizontalCenterLocation= (horizontalStartLocation + horizontalEndLocation) /2;//获取绘制区域大小
CGFloat drawSpaceWidth =[self scaleWidthOfTitleDrawSpace];
CGFloat drawSpaceHeight=[self scaleHeightOfTitleDrawSpace];
CGRect drawRect= CGRectMake(horizontalCenterLocation - drawSpaceWidth/2.0, self.frame.size.height/2.0 - drawSpaceHeight/2.0, drawSpaceWidth, drawSpaceHeight);
[test drawInRect:drawRect];
重点 -> 文字居中时,用 NSMutableParagraphStyle 去设定。
2.绘制下划线和分割线
CGContextRef context =UIGraphicsGetCurrentContext();
CGContextMoveToPoint(context, horizontalStartLocation, self.frame.size.height);
CGContextAddLineToPoint(context, horizontalEndLocation, self.frame.size.height);if(hasUnderline) {
CGContextSetRGBStrokeColor(context,43/255, 128.0/255, 233.0/255, 1);
CGContextSetLineWidth(context,2);
}else{
CGContextSetRGBStrokeColor(context,228.0/255, 228.0/255, 228.0/255, 1);
CGContextSetLineWidth(context,1);
}
CGContextStrokePath(context);
重点在于quartz的使用。
3.感应选择的区域 -> 通过添加gesture识别手势。
- (void)awakeFromNib {
[super awakeFromNib];
UITapGestureRecognizer *gesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapTouch:)];
[self addGestureRecognizer:gesture];
}
识别方法以及辅助的判断方法:
#pragma mark - 点击事件监听
- (void)tapTouch:(UITapGestureRecognizer *)recognizer {if(recognizer.state ==UIGestureRecognizerStateEnded) {//获取下一个选择的选项是哪个
NSInteger nextLocation =[self judgeTapSpace:[recognizer locationInView:self].x];//如果选择的选项改变了。调用回调函数
if(self.selectedLocation !=nextLocation) {
self.selectAction(nextLocation);
}
self.selectedLocation=nextLocation;
}
}-(NSInteger)judgeTapSpace:(CGFloat)horizontalLocation {return (NSInteger) (horizontalLocation /(self.frame.size.width /[self.titleArray count]));
}
具体函数以及使用方法移步github: 我的github