JAK
JAK

Reputation: 6471

How to set UIPageControl with image in iOS8 Objective c?

I want to set UIPageControl with images in the place of dots. I implemented the following code but it always crashing.Please help me.

-(void)updateDots
{
    for (int i=0; i<[_pageControl.subviews count]; i++) {

    UIImageView *dot = [_pageControl.subviews objectAtIndex:i];
    if (i==_pageControl.currentPage)
        dot.image = [UIImage imageNamed:@"on.png"];
    else
        dot.image = [UIImage imageNamed:@"off.png"];

   }
}

In iOS8,i got the following error *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[UIView setImage:]: unrecognized selector sent to instance 0x7f9dd9eaabb0'

Upvotes: 0

Views: 1994

Answers (3)

SomeGuy
SomeGuy

Reputation: 9690

You shouldn't assume that the UIPageControl will contain UIImageViews (it doesn't).

Here's how to do this with public APIs:

- (void)updateDots
{
    // this only needs to be done one time
    // 7x7 image (@1x)
    _pageControl.currentPageIndicatorTintColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"on.png"]];
    _pageControl.pageIndicatorTintColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"off.png"]];
}

Upvotes: 1

gran_profaci
gran_profaci

Reputation: 8463

Remember, subviews don't always have to be UIImageViews. For example, UITableViewCells often have enclosing views or so within them. You need to make the change below.

-(void)updateDots
{
    for (int i=0; i<[_pageControl.subviews count]; i++) {

    if ([[_pageControl.subviews objectAtIndex:i] isKindOfClass:[UIImageView Class]]) 
    {
        UIImageView *dot = (UIImageView *)[_pageControl.subviews objectAtIndex:i];
        if (i==_pageControl.currentPage)
            dot.image = [UIImage imageNamed:@"on.png"];
        else
            dot.image = [UIImage imageNamed:@"off.png"];
        }
    }        
}

I've noticed that in a UITableViewCell, there is always an enclosing UIView for the cell content. You need to recursively go into this view to find the UIImageView you are looking for.

Upvotes: 0

ChintaN -Maddy- Ramani
ChintaN -Maddy- Ramani

Reputation: 5164

you are getting UIView in for loop. check if dot is UIImageView Class then set image.

id object = [_pageControl.subviews objectAtIndex:i];
if([object isKindOfClass:[UIImageView Class]])
{
    UIImageView *dot = (UIImageView *)object;
    if (i==_pageControl.currentPage)
        dot.image = [UIImage imageNamed:@"on.png"];
    else
        dot.image = [UIImage imageNamed:@"off.png"];
}

Hope it will help you.

Upvotes: 0

Related Questions