IOS之自定义平铺导航UIScrollView+UIPageControl
MyPageView是自定义的UIView。实现效果如下。
?
1.MyPageView.h
#import <UIKit/UIKit.h>@interface MyPageView : UIView<UIScrollViewDelegate>@property(strong,nonatomic) UIScrollView* scrollView;@property (strong, nonatomic) IBOutlet UIPageControl *pageControl;-(void)initPageViewWithViewController:(UIViewController*)controller imagePaths:(NSArray*)imagePathArr;@end
?2.MyPageView.m
#import "MyPageView.h"@implementation MyPageView- (id)initWithFrame:(CGRect)frame{ self = [super initWithFrame:frame]; if (self) { // Initialization code } return self;}-(void)initPageViewWithViewController:(UIViewController*)controller imagePaths:(NSArray*)imagePathArr{ NSInteger count = [imagePathArr count]; CGFloat height = self.frame.size.height; CGFloat width = self.frame.size.width; self.scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, width, height)]; self.scrollView.contentSize = CGSizeMake(width*count, height); self.scrollView.showsVerticalScrollIndicator = FALSE; self.scrollView.showsHorizontalScrollIndicator = FALSE; //important [self.scrollView setPagingEnabled:YES]; [self addSubview:self.scrollView]; CGFloat pageControlWidth = 10.0f * count; CGFloat pageControlHeight = 15.0f; self.pageControl = [[UIPageControl alloc] initWithFrame:CGRectMake((width - pageControlWidth) / 2, height - pageControlHeight, pageControlWidth, pageControlHeight)]; [self.pageControl setCurrentPage:0]; [self.pageControl setNumberOfPages:count]; [self.pageControl addTarget:self action:@selector(changePage:) forControlEvents:UIControlEventValueChanged]; [self addSubview:self.pageControl]; NSInteger index = 0; for(NSString *imagePath in imagePathArr){ CGFloat xPos = index * width; UIImageView* imageView = [[UIImageView alloc] initWithFrame:CGRectMake(xPos, 0, width, height)]; imageView.image = [UIImage imageNamed:imagePath]; [self.scrollView addSubview:imageView]; index++; } //implement UIScrollViewDelegate self.scrollView.delegate = self;}- (void) scrollViewDidScroll: (UIScrollView *) aScrollView{ CGFloat width = self.frame.size.width;CGPoint offset = aScrollView.contentOffset;self.pageControl.currentPage = offset.x / width;}//在点击pageControl时调用- (IBAction)changePage:(id)sender{ CGFloat width = self.frame.size.width; [UIView animateWithDuration:0.3f animations:^{ int whichPage = self.pageControl.currentPage; self.scrollView.contentOffset = CGPointMake(width * whichPage, 0.0f); }];}@end
?3.调用方法
MyPageView* pageView = [[MyPageView alloc] initWithFrame:CGRectMake(0,44.0f,320.0f,140.0f)]; NSMutableArray* arr = [NSMutableArray array]; [arr addObject:@"m1.png"]; [arr addObject:@"m2.png"]; [pageView initPageViewWithViewController:self imagePaths:arr]; [self.view addSubview:pageView];
?