• 注册
当前位置:1313e > 默认分类 >正文

自定义UIPageControl 控件(二)

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

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

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

#import

#import

 

@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

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;

 

}

}


本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 162202241@qq.com 举报,一经查实,本站将立刻删除。

最新评论

欢迎您发表评论:

请登录之后再进行评论

登录
相关推荐