首页 > ios 自定义UIPageControl选中 非选中的相对位置问题

ios 自定义UIPageControl选中 非选中的相对位置问题

.h文件

import <UIKit/UIKit.h>

@interface MyPageControl : UIPageControl

@end
.m文件

import "MyPageControl.h"

import "UIView+Layout.h"

@implementation MyPageControl

-(id) initWithFrame:(CGRect)frame{

self = [super initWithFrame:frame];

return self;

}

-(void) updateDots
{

for (int i = 0; i < [self.subviews count]; i++)
{
   UIImageView* dot = [self.subviews objectAtIndex:i];
    
    NSLog(@"dot:%@",dot);
    
    if (i == self.currentPage) {
        dot.height = 4;
        dot.width = 10;
        dot.layer.cornerRadius = 2;
        dot.y = floorf((self.bounds.size.height - 4)/2.0);
    }else{
        
        dot.height = 1.5;
        dot.width = 10;
        dot.layer.cornerRadius = 0.75;
        dot.y = floorf((self.bounds.size.height - 1.5)/2.0);
    }
}

}

-(void) setCurrentPage:(NSInteger)page
{

[super setCurrentPage:page];
[self updateDots];

}

@end

然后这是调用
CGFloat w = self.view.frame.size.width;

    CGFloat h = self.view.frame.size.height;
    _pageControl = [[MyPageControl alloc] init];
    _pageControl.center = CGPointMake(w * 0.5, h - 20);
    _pageControl.bounds = CGRectMake(0, 0, 150, 50);
    _pageControl.numberOfPages = 3; // 一共显示多少个圆点(多少页)
    // 设置非选中页的圆点颜色
    _pageControl.pageIndicatorTintColor = NotSeclect_Page_Color1;
    // 设置选中页的圆点颜色
    _pageControl.currentPageIndicatorTintColor = Seclect_Page_Color1;

    // 禁止默认的点击功能
    _pageControl.enabled = NO;

    [self.view addSubview:_pageControl];
    
    这是滑动调用
    • (void)scrollViewDidScroll:(UIScrollView *)scrollView
      {

    1. page = scrollView.contentOffset.x / scrollView.frame.size.width;
      // NSLog(@"%d", page);

      // 设置页码
      _pageControl.currentPage = page;
      }
      然后显示效果如图:

    可以看到后面两个并没有居中

    可是稍微轻轻一滑动 就好了 如图:

    这是为什么 求解答 为什么 不能一显示就是如图2的效果


    因为你初始化的时候并没有调用updateDots这个方法,只有滑动的时候调用了,所以一滑动就正常了


    这样就可以了。。。

    【热门文章】
    【热门文章】