iPhone應用中UITableView用法總結
iPhone應用中UITableView用法總結是本文要介紹的內(nèi)容,這一節(jié)主要講解對UITableView的理解,IPhone的應用程序是離不開UITableView應用程序的,因此理解Table控件特別的重要。下面主要是對UITableView顯示數(shù)據(jù)的兩種方式進行講解。
顯示數(shù)據(jù)的內(nèi)容主要是UITableView控件,但是我們需要定義一個類為他加載數(shù)據(jù),以及定義和用戶交互交互的回調(diào)函數(shù),這兩個方面是通過委托的形式實現(xiàn)的。根據(jù)MVC的設計形式,Apple將UITableView放置到一個UITableViewController類當中,使用UITableViewController類實例來控制UITableView的更個方面的屬性。我們需要創(chuàng)建這么一個controller類型的類,這種類可以通過繼承成為UITableView的父類,也可以不繼承這個類,僅僅實現(xiàn)數(shù)據(jù)源委托以及操作委托即可。
1、創(chuàng)建基于UITableViewController的子類。
- @interface RootViewController : UITableViewController {
- NSArray *dataArray ;
- }
- @property(nonatomic,retain) NSArray *dataArray ;
因為UITableViewController類已經(jīng)包含了委托<UITableViewDelegate, UITableViewDataSource>,因此我們在這里就不需要手動添加這些委托。我們可以通過查看源代碼來查看我們的假設:
- UIKIT_EXTERN_CLASS @interface UITableViewController : UIViewController <UITableViewDelegate, UITableViewDataSource>
- {
- @private
- UITableViewStyle _tableViewStyle;
- id _keyboardSupport;
- struct {
- int clearsSelectionOnViewWillAppear:1;
- } _tableViewControllerFlags;
- }
通過上面的代碼我們可以看到UITableViewController已經(jīng)繼承了<UITableViewDelegate, UITableViewDataSource>這兩個委托。
這樣以來,在實現(xiàn)文件里面我們僅僅需要實現(xiàn)這兩個委托里面的必須實現(xiàn)的函數(shù)就可以了。
但是,到這里我們還是不可以的,我們還沒有完完成任務。 我們創(chuàng)建的這個類還是需要一個能夠裝載這個類的實例的容器來著,這就好像,我們?nèi)ベI一瓶礦泉水,水是必須裝在一個瓶子(容器)里面才可以拿著喝得。 我們創(chuàng)建的這個類的實例,就好比水,我們還需要創(chuàng)建一個瓶子(容器)來裝這些水 。這個容器可以是一個UIView實例,或者是一個UINavigationController實例,或者是一個Nib文件都可以,這些準備完畢后就可以看到效果了。
2、現(xiàn)在我們來看第二種情況,創(chuàng)建普通控制類的實例。
如果我們創(chuàng)建普通控制類的實例,比如如下面所示:
- @interface RootViewController:UITableViewController
- <UITableViewDelegate,UITableViewDataSource>
- {
- NSArray *dataArray;
- }
- @property(nonatomic,retain) NSArray *dataArray ;
這種情況下,我們需要手動的添加來繼承委托,實現(xiàn)數(shù)據(jù)源的繼承以及數(shù)據(jù)操作的繼承。
然后剩下的情況就和其他上面的一樣來,實現(xiàn)委托中定義的必須要實現(xiàn)的類,加載數(shù)據(jù),加載數(shù)據(jù)到容器中,然后顯示數(shù)據(jù)。
創(chuàng)建一個簡單的表格
參考代碼:
- //.h
- @interface ViewBaseAppViewController : UIViewController
- <UITableViewDelegate,UITableViewDataSource>
- {
- IBOutlet UITableView *m_tableView;
- }
- //.m
- - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
- // Return the number of rows in the section.
- return 10;
- }
- - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
- {
- static NSString *CellIdentifier = @"Cell";
- UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
- if (cell == nil) {
- cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
- }
- cell.textLabel.text =@"xingchen";
- return cell;
- }
小結:iPhone應用中UITableView用法總結的內(nèi)容介紹完了,希望本文對你有所幫助。