自定义UIPageControl 控件(二)

使用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;

}

}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值