平鋪導航――基于分屏導航的實現(IOS開發)
來源:程序員人生 發布時間:2014-11-11 08:56:08 閱讀次數:3052次
導航模式
-平鋪導航:內容沒有層次關系,其實就在1個主屏幕上,只是采取分屏分頁控制器來導航,可以左右上下滑動屏幕查看內容。(如:系統自帶的天氣)
-標簽導航:內容被分割幾個功能模塊,但這些功能實際上沒有任何關系。通過標簽管理。標簽利用太多太多了。。。
-樹形導航:有層次,從上到下細分為或為包括的關系。(如:郵箱)
這幾個常常組合起來1起使用。
這里主要講平鋪導航。
用到的控件為分屏控件(UIPageControl)和轉動視圖控件(ScrollView),在這個進程中我們可能確切新建了許多View Controller的視圖控制器,但是實際上其實不屬于任何子類,只是為了讓我們幾個圖片有個地方放置。
這里需要理解的是,這個app只有1個View,這個View包括了1個ScrollView,而這個ScrollView有好幾個屏那末大,每一個屏1張圖。我們在左右劃動的時候就好像有好多個View1樣,但實際真正劃動的是巨大的ScrollView。


#import <UIKit/UIKit.h>
@interface ViewController : UIViewController<UIScrollViewAccessibilityDelegate>
@property (strong, nonatomic) UIView *page1;
@property (strong, nonatomic) UIView *page2;
@property (strong, nonatomic) UIView *page3;
@property (weak, nonatomic) IBOutlet UIScrollView *scrollView;
@property (weak, nonatomic) IBOutlet UIPageControl *pageControl;
- (IBAction)changePage:(id)sender;
@end
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.scrollView.contentSize = CGSizeMake(self.view.frame.size.width*3, self.scrollView.frame.size.height);
self.scrollView.frame = self.view.frame;
// 新建SB的援用
UIStoryboard *mainStoryboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
//
// 下面的1段代碼是為了獲得項目中制定文件名的ViewController
// page1.page2.page3在h中時連不上熱門的,由于從這個角度來看他們更像是屬性
// contentsize是內容大小,而frame是視窗大小
UIViewController* page1ViewController = [mainStoryboard instantiateViewControllerWithIdentifier:@"page1"];
self.page1 = page1ViewController.view;
self.page1.frame = CGRectMake(0.0f, 0.0f, 320.0f, 420.0f);
UIViewController* page2ViewController = [mainStoryboard instantiateViewControllerWithIdentifier:@"page2"];
self.page2 = page2ViewController.view;
self.page2.frame = CGRectMake(320.0f, 0.0f, 320.0f, 420.0f);
UIViewController* page3ViewController = [mainStoryboard instantiateViewControllerWithIdentifier:@"page3"];
self.page3 = page3ViewController.view;
self.page3.frame = CGRectMake(2 * 320.0f, 0.0f, 320.0f, 420.0f);
// 需要實現UIScrollViewDelegate協議
self.scrollView.delegate = self;
[self.scrollView addSubview:self.page1];
[self.scrollView addSubview:self.page2];
[self.scrollView addSubview:self.page3];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
// 每次劃屏后,需要計算和設定分屏空間確當前屏currentPage
- (void) scrollViewDidScroll:(UIScrollView *)aScrollView
{
// offset為內容大小
CGPoint offset = aScrollView.contentOffset;
self.pageControl.currentPage = offset.x / 320.0f; // 返回當前是第幾頁
}
// 這是為了產生動畫效果
- (IBAction)changePage:(id)sender {
[UIView animateWithDuration:0.3f animations:^{
int whichPage = self.pageControl.currentPage;
self.scrollView.contentOffset = CGPointMake(320.0f*whichPage, 0.0f);
}];
}
@end
生活不易,碼農辛苦
如果您覺得本網站對您的學習有所幫助,可以手機掃描二維碼進行捐贈