[iOS]给UIPageControl设置圆点间距

** 平常用pageControl用的少,今天发现怎么setFrame,setSize,setBounds都对间距不起作用,所以跟大家分享一下在网上找到的解决办法**

  • 新建子类 @interface CyclePageControl : UIPageControl
  • 重写 - (void)layoutSubviews
#define dotW 4.5
#define activeDotW 6
#define margin 5
- (void)layoutSubviews
{
    [super layoutSubviews];
    
    //计算圆点间距
    CGFloat marginX = margin + 5;
    
    //计算整个pageControll的宽度
    CGFloat newW = (self.subviews.count - 1 ) * marginX;
    
    //设置新frame
    self.frame = CGRectMake(self.frame.origin.x, self.frame.origin.y, newW, self.frame.size.height);
    
    //设置居中
    CGPoint center = self.center;
    center.x = self.superview.center.x;
    self.center = center;
    
    //遍历subview,设置圆点frame
    for (int i=0; i<[self.subviews count]; i++) {
        UIImageView* dot = [self.subviews objectAtIndex:i];
        
        [dot setFrame:CGRectMake(i * marginX, dot.frame.origin.y, dotW, dotW)];
        
    }
}
  • 顺便一提,设置圆点照片、当前照片用KVC
 [pagecontrol setValue:[UIImage imageNamed:@"icon_xuanzhong"] forKeyPath:@"_currentPageImage"];
 [pagecontrol setValue:[UIImage imageNamed:@"icon_weixuanzhong"] forKeyPath:@"_pageImage"];

你可能感兴趣的:([iOS]给UIPageControl设置圆点间距)