代码改变世界

自定义UIPageControl 控件(二)

2011-08-10 11:33  乱世文章  阅读(528)  评论(0编辑  收藏  举报

使用UIPageControl的例子如前面所示。但光以控件形式使用 UIPageControl还是不好用,因为虽然用户能通过手指扫动UIPageControl控件进行翻页,但UIPageControl控件在屏幕上所占的区域还是太小了,如果用户在整个屏幕都能通过扫动来进行翻页就更好了,这无疑大大增强的用户的体验。

这需要我们增加一个UIView控件,让它占据屏幕的整个区域。让UIView能识别用户手指扫动的手势,即几个touchesXXX方法。这样用户在屏幕上滑动手指时,实际上会被UIView捕捉为扫动手势。

首先,我们来实现这个UIView。新建类 SwipeView。SwipeView借鉴了《iPhone开发秘籍》中 Henry Yu 的实现,甚至我们都不需要做多少改变。

#import <UIKit/UIKit.h>

#import <QuartzCore/QuartzCore.h>

 

@interface SwipeView : UIView {

CGPoint startTouchPosition;

NSString *direction;

UIViewController *host;

}

- (void) setHost: (UIViewController *) aHost;

@end

#import "SwipeView.h"

@implementation SwipeView

 

- (id)initWithFrame:(CGRect)frame {

    if ((self = [super initWithFrame:frame])) {

        // Initializationcode

    }

    return self;

}

- (void) setHost: (UIViewController *) aHost

{

host = aHost;

}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event

{

UITouch *touch = [touches anyObject];

startTouchPosition = [touch locationInView:self];

direction = NULL;

}

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event

{

UITouch *touch =touches.anyObject;

CGPoint currentTouchPosition =[touch locationInView:self];

#defineHORIZ_SWIPE_DRAG_MIN 12

#defineVERT_SWIPE_DRAG_MAX 4

if (fabsf(startTouchPosition.x -currentTouchPosition.x) >=

HORIZ_SWIPE_DRAG_MIN &&

fabsf(startTouchPosition.y - currentTouchPosition.y) <=

VERT_SWIPE_DRAG_MAX)

{

// Horizontal Swipe

if (startTouchPosition.x <currentTouchPosition.x) {

direction = kCATransitionFromLeft;

}

else

direction = kCATransitionFromRight;

}

}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event

{

if (host!=nil && direction) {

SEL sel=NSSelectorFromString(@"swipeTo:");

if([host respondsToSelector:sel]) {

[host performSelector:sel withObject:direction];

}

}

@end

 

首先,打开我们前面所做的工程UsingPageControl。

在UsingPageControlVeiwController中导入头文件SwipeView.h。将UsingPageControlViewController中的pageView修改为SwipeView类型。

同时在pageView的初始化时使用SwipeView的initWithFrame方法,并调用setHost:方法:

pageView=[[SwipeView alloc]initWithFrame:contentFrame];

[pageView setHost:self];

接下来,我们需要在SwipeView的Host类UsingPageControlVeiwController实现指定的swipeTo:方法:

// SwipeView 的协议(委托)方法

- (void) swipeTo: (NSString *) aDirection

{

NSLog(@"swipe to");

int to=previousPage;

if ([aDirection isEqualToString:kCATransitionFromRight])

{

to++;

}else {

to--;

}

if (to>=0 && to<=2) {

// pageCtrl的值改变并调用pageTuren方法

[self transitionPage:previousPage toPage:to];

previousPage=pageCtr.currentPage=to;

 

}

}