UISegmentedControl 没有代理方法可以设置,不能在选择之前做预处理。为此,重写了 UISegmentedControl
创建文件 RFSegmentedControl,继承自 UISegmentedControl,并添加代理方法 RFSegmentedControlDelegate
两个代理方法,分别为 shouldSelected 和 didSelected,如名字,表示是否可以选择和已经选择的意思。
增加 delegate 的变量
#import <UIKit/UIKit.h> @class RFSegmentedControl; @protocol RFSegmentedControlDelegate <NSObject> - (BOOL)segmentedControl:(RFSegmentedControl *)segmentedControl shouldSelectAtIndex:(NSInteger)index; - (void)segmentedControl:(RFSegmentedControl *)segmentedControl didSelectedAtIndex:(NSInteger)index; - (void)segmentedControl:(RFSegmentedControl *)segmentedControl didSelectedAtIndex:(NSInteger)index userInteracted:(BOOL)userInteracted; @end @interface RFSegmentedControl : UISegmentedControl @property (assign, nonatomic) id<RFSegmentedControlDelegate> delegate; - (void)setSelectedSegmentIndex:(NSInteger)selectedSegmentIndex ignoreNotify:(BOOL)ignore; @end
增加私有变量 preIndex,表示选择之前的index
因为没有必要暴漏给其他类,定义在 .m 文件中即可,在 selectedIndex 变化之前,保存下来 selectedIndex 的值
NSInteger preIndex;
重写两个方法:willChangeValueForKey: didChangeValueForKey:
这两个方法会分别在 selectedIndex 变化前后触发,之前,保存原有的 selectedIndex 值,之后,根据 shouldSelect 代理方法判断是否可以点击,不可以点击则将原来的值重新赋值给 selectedIndex;可以点击则触发 didSelect 代理方法。
- (void)willChangeValueForKey:(NSString *)key { if ([key isEqualToString:@"selectedSegmentIndex"]) { preIndex = self.selectedSegmentIndex; } } - (void)didChangeValueForKey:(NSString *)key { if ([key isEqualToString:@"selectedSegmentIndex"]) { BOOL shouldSelected = YES; NSInteger index = [[self valueForKey:key] integerValue]; if ([self.delegate respondsToSelector:@selector(segmentedControl:shouldSelectAtIndex:)]) { shouldSelected = [self.delegate segmentedControl:self shouldSelectAtIndex:index]; } if (shouldSelected == NO) { self.selectedSegmentIndex = preIndex; }else{ if (_ignoreSelectedNotify == NO) { if ([self.delegate respondsToSelector:@selector(segmentedControl:didSelectedAtIndex:)]) { [self.delegate segmentedControl:self didSelectedAtIndex:index]; } if ([self.delegate respondsToSelector:@selector(segmentedControl:didSelectedAtIndex:userInteracted:)]) { [self.delegate segmentedControl:self didSelectedAtIndex:index userInteracted:_userInteracted]; } } } } } - (void)setSelectedSegmentIndex:(NSInteger)selectedSegmentIndex ignoreNotify:(BOOL)ignore { _ignoreSelectedNotify = ignore;
[self setSelectedSegmentIndex:selectedSegmentIndex]; _ignoreSelectedNotify = NO; } - (void)setSelectedSegmentIndex:(NSInteger)selectedSegmentIndex { _userInteracted = NO; [super setSelectedSegmentIndex:selectedSegmentIndex]; _userInteracted = YES; }