效果如下:
ViewController.h
1 #import <UIKit/UIKit.h> 2 3 @interface ViewController : UIViewController 4 @end
ViewController.m
1 #import "ViewController.h" 2 #import "KMLabelViewController.h" 3 4 @interface ViewController () 5 - (void)layoutUI; 6 @end 7 8 @implementation ViewController 9 #define kNumberOfPages 3 10 11 - (void)viewDidLoad { 12 [super viewDidLoad]; 13 14 [self layoutUI]; 15 } 16 17 - (void)didReceiveMemoryWarning { 18 [super didReceiveMemoryWarning]; 19 // Dispose of any resources that can be recreated. 20 } 21 22 - (void)layoutUI { 23 CGFloat viewWidth = self.view.frame.size.width; 24 CGFloat viewHeight = self.view.frame.size.height; 25 26 UIScrollView *scrVCustom = [[UIScrollView alloc] initWithFrame:self.view.bounds]; 27 //为了能进行画面水平翻滚,设置滚动视图scrVCustom内容的水平长度 28 scrVCustom.contentSize = CGSizeMake(viewWidth * kNumberOfPages, viewHeight); 29 //设置是否以页为单位翻滚;默认值为NO 30 scrVCustom.pagingEnabled = YES; 31 //设置是否显示水平和垂直滚动条;默认值都为YES 32 scrVCustom.showsHorizontalScrollIndicator = YES; 33 scrVCustom.showsVerticalScrollIndicator = NO; 34 //设置是否允许滚动到顶部;默认值为YES 35 scrVCustom.scrollsToTop = NO; 36 37 //设置滚动条的颜色 38 //UIScrollViewIndicatorStyleDefault(白色框包围黑色线条,大多数背景下适用);默认值 39 //UIScrollViewIndicatorStyleBlack(黑色条) 40 //UIScrollViewIndicatorStyleWhite(白色条) 41 scrVCustom.indicatorStyle = UIScrollViewIndicatorStyleDefault; 42 43 for (NSInteger i=0; i<kNumberOfPages; i++) { 44 KMLabelViewController *lblViewController = [[KMLabelViewController alloc] initWithNumber:i]; 45 lblViewController.view.frame = CGRectMake(viewWidth * i, 0, viewWidth, viewHeight); 46 [scrVCustom addSubview:lblViewController.view]; 47 } 48 [self.view addSubview:scrVCustom]; 49 } 50 51 @end
KMLabelViewController.h
1 #import <UIKit/UIKit.h> 2 3 @interface KMLabelViewController : UIViewController 4 - (id)initWithNumber:(NSInteger)number; 5 6 @end
KMLabelViewController.m
1 #import "KMLabelViewController.h" 2 3 @interface KMLabelViewController () 4 @end 5 6 @implementation KMLabelViewController 7 8 - (void)viewDidLoad { 9 [super viewDidLoad]; 10 } 11 12 - (void)didReceiveMemoryWarning { 13 [super didReceiveMemoryWarning]; 14 // Dispose of any resources that can be recreated. 15 } 16 17 - (id)initWithNumber:(NSInteger)number { 18 if (self = [super init]) { 19 UILabel *lblCustom = [[UILabel alloc] initWithFrame:CGRectInset(self.view.bounds, 0, 0)]; 20 lblCustom.text = [NSString stringWithFormat:@"%ld", (long)number]; 21 lblCustom.textAlignment = NSTextAlignmentCenter; 22 lblCustom.textColor = [UIColor performSelector:NSSelectorFromString(number % 2 == 1 ? @"whiteColor" : @"blackColor")]; 23 lblCustom.backgroundColor = [UIColor performSelector:NSSelectorFromString(number % 2 == 1 ? @"blackColor" : @"whiteColor")]; 24 lblCustom.font = [UIFont boldSystemFontOfSize:64]; 25 [self.view addSubview:lblCustom]; 26 } 27 return self; 28 } 29 30 @end
时间: 2024-10-08 02:08:34