我正在尝试找到一种方法,用“Page X of Y”的标题替换 UIPageControl 的点,因为我可能有 >50 个项目。我刚刚熟悉 Cocoa,我想知道最好的方法是什么。我可以子类化 UIPageControl 吗?我应该使用带标签的自定义视图吗?或者是其他东西?
Edit:
我最终使用了this http://cocoawithlove.com/2009/01/multiple-virtual-pages-in-uiscrollview.htmlMatt Gallagher 编写的代码来实现我的分页视图。它也更高效,因为它重复使用两个视图,而不是像 Apple PageControl 示例代码中那样一次性创建它们。
EDIT:
这个答案得到了很多人的赞同。谢谢你,但对于所有来到这里的人,请意识到 UIPageControl 是很容易自己实现!更重要的是,请查看我的回复和下面的示例代码以获取一些想法,但您确实不应该在生产代码中使用它。如果您需要修改 UIPageControl 的外观和感觉,请滚动您自己的 UIControl 子类。
原答案:
UIPageControl 没有做任何花哨的事情。对于大多数视图,视图本身要么在 drawRect: 中完成所有绘制,要么添加子视图并自行绘制。通过重写drawRect:而不是调用[super drawRect:],您可以确保如果实现是基于drawRect:的,您将调用自己的绘图代码。对于 UIPageControl,它依赖于已添加到 UIPageControl 的子视图。您实际上不需要知道哪种类型,也不应该关心。这是 Apple 的实施,可能会发生变化。
但是因为您知道它必须是基于drawRect:或基于子视图,所以您可以简单地删除UIPageControl的子视图,然后您的drawRect:覆盖将按照您的预期工作(大多数情况下,您必须做一些事情)一些额外的工作以确保您在正确的时间重绘)。
下面的示例展示了如何制作您自己的自定义 UIPageControl。精明的读者会注意到,一旦您不厌其烦地这样做,您可能还只是创建了自己的页面控件作为 UIControl 的子类,并简单地实现了 UIPageControl API。
//
// RedGreyPageControl.m
//
@interface RedGreyPageControl : UIPageControl {
NSArray *originalSubviews;
}
@end
@implementation RedGreyPageControl
// This assumes you're creating the control from a nib. Depending on your
// usage you might do this step in initWithFrame:
- (void) awakeFromNib {
// retain original subviews in case apple's implementation
// relies on the retain count being maintained by the view's
// presence in its superview.
originalSubviews = [[NSArray alloc] initWithArray: self.subviews];
for ( UIView *view in self.subviews ) [view removeFromSuperview];
// make sure the view is redrawn not scaled when the device is rotated
self.contentMode = UIViewContentModeRedraw;
}
- (void) dealloc {
[originalSubviews release];
[super dealloc];
}
- (void) drawRect:(CGRect) iRect {
UIImage *grey, *image, *red;
int i;
CGRect rect;
const CGFloat kSpacing = 10.0;
iRect = self.bounds;
if ( self.opaque ) {
[self.backgroundColor set];
UIRectFill( iRect );
}
if ( self.hidesForSinglePage && self.numberOfPages == 1 ) return;
red = [UIImage imageNamed: @"circle_graphic_red.png"];
grey = [UIImage imageNamed: @"circle_graphic_grey.png"];
rect.size.height = red.size.height;
rect.size.width = self.numberOfPages * red.size.width + ( self.numberOfPages - 1 ) * kSpacing;
rect.origin.x = floorf( ( iRect.size.width - rect.size.width ) / 2.0 );
rect.origin.y = floorf( ( iRect.size.height - rect.size.height ) / 2.0 );
rect.size.width = red.size.width;
for ( i = 0; i < self.numberOfPages; ++i ) {
image = i == self.currentPage ? red : grey;
[image drawInRect: rect];
rect.origin.x += red.size.width + kSpacing;
}
}
// you must override the setCurrentPage: and setNumberOfPages:
// methods to ensure that your control is redrawn when its values change
- (void) setCurrentPage:(NSInteger) iPage {
[super setCurrentPage: iPage];
[self setNeedsDisplay];
}
- (void) setNumberOfPages:(NSInteger) iPages {
[super setNumberOfPages: iPages];
[self setNeedsDisplay];
}
@end
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)