代码之家  ›  专栏  ›  技术社区  ›  Tirth

如何更改uipagecontrol的分页点颜色?

  •  175
  • Tirth  · 技术社区  · 14 年前

    我正在开发一个应用程序,我想在其中更改的颜色或图像 UIPageControl 分页点。我怎样才能改变它?可以定制吗 UIpageControl 在上面的场景中?

    18 回复  |  直到 5 年前
        1
  •  259
  •   Heiberg    9 年前

    更新:

    这个答案已经6岁了,已经过时了,但仍然吸引着人们的投票和评论。从iOS 6.0开始,您应该使用 pageIndicatorTintColor currentPageIndicatorTintColor 对性能 UIPageControl .

    原始答案:

    我今天遇到这个问题,决定自己写一个简单的替换类。

    它是一个子类的uiview,使用核心图形以指定的颜色呈现点。

    您可以使用公开的属性自定义和控制它。

    如果您愿意,可以注册一个委托对象,以便在用户点击其中一个小页点时获得通知。如果未注册任何委托,则视图将不会对触摸输入做出反应。

    它是完全新鲜的烤箱,但似乎工作。如果你遇到任何问题,请告诉我。

    未来的改进:

    • 调整点的大小以适应当前 如果有太多的边界。
    • 不要在DrawRect中重新绘制整个视图:

    实例使用:

    CGRect f = CGRectMake(0, 0, 320, 20); 
    PageControl *pageControl = [[[PageControl alloc] initWithFrame:f] autorelease];
    pageControl.numberOfPages = 10;
    pageControl.currentPage = 5;
    pageControl.delegate = self;
    [self addSubview:pageControl];
    

    头文件:

    //
    //  PageControl.h
    //
    //  Replacement for UIPageControl because that one only supports white dots.
    //
    //  Created by Morten Heiberg <morten@heiberg.net> on November 1, 2010.
    //
    
    #import <UIKit/UIKit.h>
    
    @protocol PageControlDelegate;
    
    @interface PageControl : UIView 
    {
    @private
        NSInteger _currentPage;
        NSInteger _numberOfPages;
        UIColor *dotColorCurrentPage;
        UIColor *dotColorOtherPage;
        NSObject<PageControlDelegate> *delegate;
        //If ARC use __unsafe_unretained id delegate;
    }
    
    // Set these to control the PageControl.
    @property (nonatomic) NSInteger currentPage;
    @property (nonatomic) NSInteger numberOfPages;
    
    // Customize these as well as the backgroundColor property.
    @property (nonatomic, retain) UIColor *dotColorCurrentPage;
    @property (nonatomic, retain) UIColor *dotColorOtherPage;
    
    // Optional delegate for callbacks when user taps a page dot.
    @property (nonatomic, retain) NSObject<PageControlDelegate> *delegate;
    
    @end
    
    @protocol PageControlDelegate<NSObject>
    @optional
    - (void)pageControlPageDidChange:(PageControl *)pageControl;
    @end
    

    实施文件:

    //
    //  PageControl.m
    //
    //  Replacement for UIPageControl because that one only supports white dots.
    //
    //  Created by Morten Heiberg <morten@heiberg.net> on November 1, 2010.
    //
    
    #import "PageControl.h"
    
    // Tweak these or make them dynamic.
    #define kDotDiameter 7.0
    #define kDotSpacer 7.0
    
    @implementation PageControl
    
    @synthesize dotColorCurrentPage;
    @synthesize dotColorOtherPage;
    @synthesize delegate;
    
    - (NSInteger)currentPage
    {
        return _currentPage;
    }
    
    - (void)setCurrentPage:(NSInteger)page
    {
        _currentPage = MIN(MAX(0, page), _numberOfPages-1);
        [self setNeedsDisplay];
    }
    
    - (NSInteger)numberOfPages
    {
        return _numberOfPages;
    }
    
    - (void)setNumberOfPages:(NSInteger)pages
    {
        _numberOfPages = MAX(0, pages);
        _currentPage = MIN(MAX(0, _currentPage), _numberOfPages-1);
        [self setNeedsDisplay];
    }
    
        - (id)initWithFrame:(CGRect)frame
    {
        if ((self = [super initWithFrame:frame]))
        {
            // Default colors.
            self.backgroundColor = [UIColor clearColor];
            self.dotColorCurrentPage = [UIColor blackColor];
            self.dotColorOtherPage = [UIColor lightGrayColor];
    
            UISwipeGestureRecognizer *swipeRight = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(swipedRight:)];
            [swipeRight setDirection:UISwipeGestureRecognizerDirectionRight];
            [self addGestureRecognizer:swipeRight];
    
    
    
    
            UISwipeGestureRecognizer *swipe = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(swipedLeft:)];
            [swipe setDirection:UISwipeGestureRecognizerDirectionLeft];
            [self addGestureRecognizer:swipe];
    
        }
        return self;
    }
    -(void) swipedLeft:(UISwipeGestureRecognizer *) recognizer
    {
        self.currentPage++;
    }
    -(void) swipedRight:(UISwipeGestureRecognizer *) recognizer
    {
        self.currentPage--;
    }
    
    - (void)drawRect:(CGRect)rect 
    {
        CGContextRef context = UIGraphicsGetCurrentContext();   
        CGContextSetAllowsAntialiasing(context, true);
    
        CGRect currentBounds = self.bounds;
        CGFloat dotsWidth = self.numberOfPages*kDotDiameter + MAX(0, self.numberOfPages-1)*kDotSpacer;
        CGFloat x = CGRectGetMidX(currentBounds)-dotsWidth/2;
        CGFloat y = CGRectGetMidY(currentBounds)-kDotDiameter/2;
        for (int i=0; i<_numberOfPages; i++)
        {
            CGRect circleRect = CGRectMake(x, y, kDotDiameter, kDotDiameter);
            if (i == _currentPage)
            {
                CGContextSetFillColorWithColor(context, self.dotColorCurrentPage.CGColor);
            }
            else
            {
                CGContextSetFillColorWithColor(context, self.dotColorOtherPage.CGColor);
            }
            CGContextFillEllipseInRect(context, circleRect);
            x += kDotDiameter + kDotSpacer;
        }
    }
    
    - (void)dealloc 
    {
        [dotColorCurrentPage release];
        [dotColorOtherPage release];
        [delegate release];
        [super dealloc];
    }
    
    - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
    {
        if (!self.delegate) return;
    
        CGPoint touchPoint = [[[event touchesForView:self] anyObject] locationInView:self];
    
        CGFloat dotSpanX = self.numberOfPages*(kDotDiameter + kDotSpacer);
        CGFloat dotSpanY = kDotDiameter + kDotSpacer;
    
        CGRect currentBounds = self.bounds;
        CGFloat x = touchPoint.x + dotSpanX/2 - CGRectGetMidX(currentBounds);
        CGFloat y = touchPoint.y + dotSpanY/2 - CGRectGetMidY(currentBounds);
    
        if ((x<0) || (x>dotSpanX) || (y<0) || (y>dotSpanY)) return;
    
        self.currentPage = floor(x/(kDotDiameter+kDotSpacer));
        if ([self.delegate respondsToSelector:@selector(pageControlPageDidChange:)])
        {
            [self.delegate pageControlPageDidChange:self];
        }
    }
    
    @end
    
        2
  •  148
  •   Matthias Bauch    11 年前

    在iOS 6中,您可以设置 UIPageControl :

    有两个新属性:

    • pageIndicatorTintColor
    • currentPageIndicatorTintColor

    还可以使用外观API更改所有页面指示器的淡色。

    如果您的目标是iOS 5,请确保它不会崩溃:

    if ([pageControl respondsToSelector:@selector(setPageIndicatorTintColor:)]) {
        pageControl.pageIndicatorTintColor = [UIColor whiteColor];
    }
    
        3
  •  40
  •   user1349663    11 年前
    pageControl.pageIndicatorTintColor = [UIColor redColor];
    pageControl.currentPageIndicatorTintColor = [UIColor redColor];
    

    IOS6的作品

        4
  •  23
  •   Ben G    12 年前

    如果有人想要ARC/Modern版本的IT(不需要将属性重新定义为IVAR,不需要DealLoc,并且使用接口生成器):

    #import <UIKit/UIKit.h>
    
    @protocol PageControlDelegate;
    
    @interface PageControl : UIView 
    
    // Set these to control the PageControl.
    @property (nonatomic) NSInteger currentPage;
    @property (nonatomic) NSInteger numberOfPages;
    
    // Customize these as well as the backgroundColor property.
    @property (nonatomic, strong) UIColor *dotColorCurrentPage;
    @property (nonatomic, strong) UIColor *dotColorOtherPage;
    
    // Optional delegate for callbacks when user taps a page dot.
    @property (nonatomic, weak) NSObject<PageControlDelegate> *delegate;
    
    @end
    
    @protocol PageControlDelegate<NSObject>
    @optional
    - (void)pageControlPageDidChange:(PageControl *)pageControl;
    @end
    

    页面控制:

    #import "PageControl.h"
    
    
    // Tweak these or make them dynamic.
    #define kDotDiameter 7.0
    #define kDotSpacer 7.0
    
    @implementation PageControl
    
    @synthesize dotColorCurrentPage;
    @synthesize dotColorOtherPage;
    @synthesize currentPage;
    @synthesize numberOfPages;
    @synthesize delegate;
    
    - (void)setCurrentPage:(NSInteger)page
    {
        currentPage = MIN(MAX(0, page), self.numberOfPages-1);
        [self setNeedsDisplay];
    }
    
    - (void)setNumberOfPages:(NSInteger)pages
    {
        numberOfPages = MAX(0, pages);
        currentPage = MIN(MAX(0, self.currentPage), numberOfPages-1);
        [self setNeedsDisplay];
    }
    
    - (id)initWithFrame:(CGRect)frame 
    {
        if (self = [super initWithFrame:frame]) 
        {
            // Default colors.
            self.backgroundColor = [UIColor clearColor];
            self.dotColorCurrentPage = [UIColor blackColor];
            self.dotColorOtherPage = [UIColor lightGrayColor];
        }
        return self;
    }
    
    -(id)initWithCoder:(NSCoder *)aDecoder
    {
        if (self = [super initWithCoder:aDecoder])
        {
            self.dotColorCurrentPage = [UIColor blackColor];
            self.dotColorOtherPage = [UIColor lightGrayColor];
        }
        return self;
    }
    
    - (void)drawRect:(CGRect)rect 
    {
        CGContextRef context = UIGraphicsGetCurrentContext();   
        CGContextSetAllowsAntialiasing(context, true);
    
        CGRect currentBounds = self.bounds;
        CGFloat dotsWidth = self.numberOfPages*kDotDiameter + MAX(0, self.numberOfPages-1)*kDotSpacer;
        CGFloat x = CGRectGetMidX(currentBounds)-dotsWidth/2;
        CGFloat y = CGRectGetMidY(currentBounds)-kDotDiameter/2;
        for (int i=0; i<self.numberOfPages; i++)
        {
            CGRect circleRect = CGRectMake(x, y, kDotDiameter, kDotDiameter);
            if (i == self.currentPage)
            {
                CGContextSetFillColorWithColor(context, self.dotColorCurrentPage.CGColor);
            }
            else
            {
                CGContextSetFillColorWithColor(context, self.dotColorOtherPage.CGColor);
            }
            CGContextFillEllipseInRect(context, circleRect);
            x += kDotDiameter + kDotSpacer;
        }
    }
    
    
    - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
    {
        if (!self.delegate) return;
    
        CGPoint touchPoint = [[[event touchesForView:self] anyObject] locationInView:self];
    
        CGFloat dotSpanX = self.numberOfPages*(kDotDiameter + kDotSpacer);
        CGFloat dotSpanY = kDotDiameter + kDotSpacer;
    
        CGRect currentBounds = self.bounds;
        CGFloat x = touchPoint.x + dotSpanX/2 - CGRectGetMidX(currentBounds);
        CGFloat y = touchPoint.y + dotSpanY/2 - CGRectGetMidY(currentBounds);
    
        if ((x<0) || (x>dotSpanX) || (y<0) || (y>dotSpanY)) return;
    
        self.currentPage = floor(x/(kDotDiameter+kDotSpacer));
        if ([self.delegate respondsToSelector:@selector(pageControlPageDidChange:)])
        {
            [self.delegate pageControlPageDidChange:self];
        }
    }
    
    @end
    
        5
  •  15
  •   ChristophK    13 年前

    Heiberg提供的答案非常有效,但是页面控件的行为并不完全像苹果提供的那样。

    如果希望页面控件的行为与Apple的相同(如果触摸下半部分,则始终将当前页面增加一个,否则将减少一个),请尝试使用此ToucheSbegan方法:

    - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    
        CGPoint touchPoint = [[[event touchesForView:self] anyObject] locationInView:self];
    
        CGRect currentBounds = self.bounds;
        CGFloat x = touchPoint.x - CGRectGetMidX(currentBounds);
    
        if(x<0 && self.currentPage>=0){
            self.currentPage--;
            [self.delegate pageControlPageDidChange:self]; 
        }
        else if(x>0 && self.currentPage<self.numberOfPages-1){
            self.currentPage++;
            [self.delegate pageControlPageDidChange:self]; 
        }   
    }
    
        6
  •  8
  •   posha    11 年前

    将以下代码添加到AppDelegate中的DidFinishLauch,

    UIPageControl *pageControl = [UIPageControl appearance];
    pageControl.pageIndicatorTintColor = [UIColor lightGrayColor];
    pageControl.currentPageIndicatorTintColor = [UIColor blackColor];
    pageControl.backgroundColor = [UIColor whiteColor];
    

    希望这会有所帮助。

        7
  •  6
  •   Pooja Patel    9 年前

    用于编码

    if([pagecontrol respondstoselector:@selector(setpageIndicatorTintColor:)){
    pageControl.pageIndicatorTintcolor=[uicolor whitecolor];
    }
    < /代码> 
    
    

    或者从故事板,您可以从当前页面颜色更改

    或者从故事板,您可以从当前页面色调更改

    enter image description here

        8
  •  5
  •   aToz    10 年前

    添加到现有答案中,可以这样做:

        9
  •  5
  •   Pang Ajmal PraveeN    7 年前

    在swift中,uipageviewcontroller内的代码正在获取对页面指示器的引用并设置其属性

    override func viewDidLoad() {
        super.viewDidLoad()
    
        //Creating the proxy
        let pageControl = UIPageControl.appearance()
        //Customizing
        pageControl.pageIndicatorTintColor = UIColor.lightGrayColor()
        pageControl.currentPageIndicatorTintColor = UIColor.darkGrayColor()
        //Setting the background of the view controller so the dots wont be on a black background   
        self.view.backgroundColor = UIColor.whiteColor()
    }
    
        10
  •  4
  •   josliber Martin Ballet    9 年前

    使用Swift 1.2很容易:

    UIPageControl.appearance().pageIndicatorTintColor           = UIColor.lightGrayColor()
    UIPageControl.appearance().currentPageIndicatorTintColor    = UIColor.redColor()
    
        11
  •  4
  •   honk    6 年前

    您可以通过将以下代码添加到 AppDeavig.m 在您的文件 didFinishLaunchingWithOptions 方法:

    UIPageControl *pageControl = [UIPageControl appearance];
    pageControl.pageIndicatorTintColor = [UIColor darkGrayColor];
    pageControl.currentPageIndicatorTintColor = [UIColor orangeColor];
    pageControl.backgroundColor = [UIColor whiteColor]
    
        12
  •  3
  •   Sid    11 年前

    这在iOS 7中对我有效。

    pageControl.pageIndicatorTintColor = [UIColor purpleColor];
    pageControl.currentPageIndicatorTintColor = [UIColor magentaColor];
    
        13
  •  2
  •   Jasarien    14 年前

    从官方的角度来看,使用iPhone SDK是不可能的。你也许可以使用私人方法,但这将是进入应用商店的障碍。

    另一个安全的解决方案是创建自己的页面控件,由于页面控件只显示滚动视图中当前显示的页面,因此创建该控件并不太困难。

        14
  •  2
  •   dsaw    13 年前

    @Jasarien我认为您可以对uipagecontrol子类,仅从Apple Doc中选取的行“自定义页面控件外观的子类可以使用此方法在页面计数更改时调整页面控件的大小”,对于方法sizeForNumberOfPages:

        15
  •  2
  •   cschuff    13 年前

    您还可以使用包含可样式的pagecontrol和数十个其他有用的UI控件和抽象的three20库。

        16
  •  1
  •   Sohil R. Memon    9 年前

    在案件中 Swift 2.0 向上,下面的代码将起作用:

    pageControl.pageIndicatorTintColor = UIColor.whiteColor()
    pageControl.currentPageIndicatorTintColor = UIColor.redColor()
    
        17
  •  0
  •   CodenameDuchess    8 年前

    这里有一个Swift 3.0解决方案…你知道,如果你同意接受声明的风险:“修改现有控件的子视图是脆弱的”。

    您必须在viewDidAppear()中调用updatedots()和页面控件的ValueChanged处理程序。

     import UIKit
    
     class CustomImagePageControl: UIPageControl {
    
       let activeImage:UIImage = UIImage(named: "SelectedPage")!
       let inactiveImage:UIImage = UIImage(named: "UnselectedPage")!
    
       override func awakeFromNib() {
             super.awakeFromNib()
    
             self.pageIndicatorTintColor = UIColor.clear
             self.currentPageIndicatorTintColor = UIColor.clear
             self.clipsToBounds = false
        }
    
        func updateDots() {
             var i = 0
             for view in self.subviews {
                 if let imageView = self.imageForSubview(view) {
                     if i == self.currentPage {
                         imageView.image = self.activeImage
                     } else {
                         imageView.image = self.inactiveImage
                     }
                     i = i + 1
                 } else {
                     var dotImage = self.inactiveImage
                     if i == self.currentPage {
                         dotImage = self.activeImage
                     }
                     view.clipsToBounds = false
                     view.addSubview(UIImageView(image:dotImage))
                     i = i + 1
                 }
             }
         }
    
         fileprivate func imageForSubview(_ view:UIView) -> UIImageView? {
             var dot:UIImageView?
    
             if let dotImageView = view as? UIImageView {
                 dot = dotImageView
             } else {
                 for foundView in view.subviews {
                     if let imageView = foundView as? UIImageView {
                         dot = imageView
                         break
                     }
                 }
             }
    
             return dot
         }
     }
    
        18
  •  -1
  •   kleopatra Aji kattacherry    11 年前
    myView.superview.tintColor = [UIColor colorWithRed:1.0f  
                                          green:1.0f blue:1.0f alpha:1.0f];