美文网首页
willMoveToSuperview的使用

willMoveToSuperview的使用

作者: 搬码小能手 | 来源:发表于2021-01-25 19:18 被阅读0次
IMB_T2vSgG.GIF
- (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];
    
}

相关文章

网友评论

      本文标题:willMoveToSuperview的使用

      本文链接:https://www.haomeiwen.com/subject/znpizktx.html