【问题标题】:How to set UIPageControl with image in iOS8 Objective c?如何在 iOS8 Objective c 中使用图像设置 UIPageControl?
【发布时间】:2015-09-16 07:06:16
【问题描述】:
我想用图像代替点来设置UIPageControl。我实现了以下代码,但它总是崩溃。请帮助我。
-(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"];
}
}
在 iOS8 中,我收到以下错误
*** 由于未捕获的异常“NSInvalidArgumentException”而终止应用程序,原因:“-[UIView setImage:]:
无法识别的选择器发送到实例 0x7f9dd9eaabb0'
【问题讨论】:
标签:
ios
objective-c
iphone
xcode6
uipagecontrol
【解决方案1】:
您不应该假设UIPageControl 将包含UIImageViews(它没有)。
以下是使用公共 API 的方法:
- (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"]];
}
【解决方案2】:
您正在 for 循环中获取 UIView。检查点是否为UIImageView Class 然后设置图像。
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"];
}
希望对你有所帮助。
【解决方案3】:
请记住,子视图不必总是UIImageViews。例如,UITableViewCells 通常在其中包含封闭视图。您需要在下面进行更改。
-(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"];
}
}
}
我注意到在UITableViewCell 中,单元格内容总是有一个封闭的UIView。你需要递归进入这个视图才能找到你要找的UIImageView。