- (void)willMoveToSuperview:(nullable UIView *)newSuperview;
核心代码
#import "WJExamingNavbar.h"
@interface WJExamingNavbar ()
@property (nonatomic,strong)UILabel * title;
@property (nonatomic,strong)UIScrollView * superScrollView;
@end
@implementation WJExamingNavbar
- (instancetype)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
[self createUI];
}
return self;
}
- (void)willMoveToSuperview:(UIView *)newSuperview{
[super willMoveToSuperview:newSuperview];
if ([newSuperview isKindOfClass:[UIScrollView class]]) {
self.superScrollView = (UIScrollView*)newSuperview;
[self.superScrollView addObserver:self forKeyPath:@"contentOffset" options:0 context:nil];
}
}
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context{
CGFloat offsetX = self.superScrollView.contentOffset.x;
NSInteger num = self.superScrollView.contentSize.width / self.width;
// 获取当前页面的索引
NSInteger index = offsetX / self.width + 0.5;
self.navTitle.text = [NSString stringWithFormat:@"%ld / %ld",(long)index + 1,(long)num];
}