UITableView -- 實現類QQ主界面

開發環境:Xcode4.5.


UITableView 是iOS UI框架裏應用非常廣泛的一個控件,基於UITableView可以實現很多漂亮而又整潔的界面。本文介紹如何實現一個類QQ好友界面。


一、建立一個Single View Application工程,命名爲QQUITableView.

1.從控件框裏面拖一個UITableView控件到View上面。 Xcode從4.5開始支持Auto layout,在Objects區域裏面可以看到多了一個Constraints對象,如果你的開發用手機iOS版本低於6.0的話,需要勾掉這個選項(Xcode File inspector裏面可以看到Interface Builder Document, 去掉Use Autolayout前面的勾)。


二、爲UITableView創建CustomCell

1.新建一個Objective-C class,命名爲 CustomCell1。在設置嚮導裏需要選擇Subclass of 爲 UITableViewCell.

2.創建相應的xib文件,命名爲CustomCell1。

3.關聯CustomCell1類。

選中CustomCell1.xib文件。然後在右邊的Inspector區域選擇Identity Inspector,在Custom Class下拉框裏面選擇剛纔建立的CustomCell1類。

4.設置重用ID

在Attributes Inspector裏面設置Identifier爲CustomCellIdentifier1. 這個identifier是用於後面代碼裏引用該UITableViewCell的。

5.其他設置爲默認。

6.在CustomCell1.h裏面添加控件變量 :

@property (retain, nonatomic) IBOutlet UILabel *nickName;
@property (retain, nonatomic) IBOutlet UIImageView *profileIcon;
@property (retain, nonatomic) IBOutlet UITextView *signature;

添加方法爲:雙擊CustomCell1.h文件會單獨打開這個文件,然後右鍵點擊控件拖動鼠標到CustomCell1.h。如下圖所示:


鬆開鼠標後,在彈出的對話框裏選擇IBOutlet, 輸入相應的變量名。這一步建立了控件和代碼之間的聯繫。後面會用到這些變量。


三、雙擊另外打開ViewController.h,用上面同樣的方法爲View中的UITableView添加變量myTableView.

@property (retain, nonatomic) IBOutlet UITableView *myTableView;

並且,要讓ViewController類實現<UITableViewDataSource,UITableViewDelegate> 這兩個協議,即:

@interface ViewController : UIViewController <UITableViewDataSource, UITableViewDelegate>{ 
}


四、設置dataSource, delegate.如下圖實。

     
界面準備工作已經做完,下面就是代碼相關的邏輯實現了。


五、在ViewController.m文件中需要實現幾個協議。

//每個section有多少行

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section ;

//UITableView表裏有多少個section

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView;

//section header的高度

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section;

//section header的視圖佈局,重載這個函數可以定製自己想要的header界面。

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section;

//控制cell的工作在這一函數裏實現,包括cell的視圖佈局,accessory的顯示等。參數indexPath指定了cell的具體位置,哪一個section, 哪一個row.

- (UITableViewCell *)tableView: (UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath;

//row 的高度

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath;


本文只用到上面幾個協議函數,其他的協議函數根據不同的需求可以自己去再做深入研究。最終效果圖如下:

           

六、代碼下載:http://download.csdn.net/detail/lovefqing/4844317


若本文和代碼有任何錯誤,歡迎拍磚指正!



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章