UIPageControl [UIView setImage:]崩溃

崩溃原因

-[UIView setImage:]: unrecognized selector sent to instance 0x11be32340

崩溃堆栈:

0 CoreFoundation    ___exceptionPreprocess + 124
1 libobjc.A.dylib   objc_exception_throw + 56
2 CoreFoundation    +[NSException raise:format:]
3 Foundation    -[NSAssertionHandler handleFailureInMethod:object:file:lineNumber:description:] + 112
6 CoreFoundation    ____forwarding___ + 624
7 CoreFoundation    _CF_forwarding_prep_0 + 92
8 UIKit -[UIPageControl _transitionIndicator:toEnabled:index:legible:] + 168
9 UIKit -[UIPageControl _transitionIndicator:toEnabled:index:] + 96
10 UIKit    -[UIPageControl _setDisplayedPage:] + 132

原因是 产品需求 要改 UIPageControl 的样式,但是系统没有给方法,所以参照网上的方法,调用私有 api,设置_pageImage_currentPageImage

 [pageControl setValue:[UIImage imageNamed:@"currentPageImage"] forKeyPath:@"_currentPageImage"];
 [pageControl setValue:[UIImage imageNamed:@"pageImage"] forKeyPath:@"_pageImage"];

完了之后一切都很正常,样式也修改了,但是莫名其妙总是偶尔会有崩溃。查看日志是发现 在 pageControl.currentPage = index; 时,pageControl 的 subview 还是 UIView,并不是 UIImageView。

打印日志发现 UIPageControl 的 subView,在初始化的时候是 UIView,但是到了显示的时候就变成了 UIImageView,这里崩溃的时候是不知为何没有变成 UIImageView。

知道了问题。那么解决方案就是换一种实现自己建立 UIImageView 覆盖在 UIPageControl 上面:

//overide the setCurrentPage
-(void) setCurrentPage:(NSInteger)page
{
    [super setCurrentPage:page];
    [self updateDots];
}

- (void)updateDots
{
    for (int i = 0; i < [self.subviews count]; i++)
    {
        UIImageView * dot = [self imageViewForSubview:  [self.subviews objectAtIndex: i]];
        if (i == self.currentPage) dot.image = self.activeImage;
        else dot.image = self.inactiveImage;
    }
}

- (UIImageView *)imageViewForSubview: (UIView *) view
{
    UIImageView * dot = nil;
    if ([view isKindOfClass: [UIView class]])
    {
        for (UIView* subview in view.subviews)
        {
            if ([subview isKindOfClass:[UIImageView class]])
            {
                dot = (UIImageView *)subview;
                break;
            }
        }
        if (dot == nil)
        {
            dot = [[UIImageView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, view.frame.size.width, view.frame.size.height)];
            [view addSubview:dot];
        }
    }
    else
    {
        dot = (UIImageView *) view;
    }
    
    return dot;
}

参考:

  1. https://stackoverflow.com/questions/12190147/customize-dot-with-image-of-uipagecontrol-at-index-0-of-uipagecontrol
  2. http://m.blog.csdn.net/u010831736/article/details/49336933

你可能感兴趣的:(UIPageControl [UIView setImage:]崩溃)