在我們的日常工作,用到最多的應該就屬于UITableView
。大家可能最熟悉的使用方式,也許就是實現UITableViewDataSource
和UITableViewDelegate
的幾種方法。那下面除了介紹這些基本的方法外,再介紹幾種簡單的,但是可能不怎么經常用的方式。
1、UITableViewDataSource
的使用
在實現UITableViewDataSource
的時候,有幾個方法是必須要實現的,直接上代碼:
// 這兩個方法是必須要實現的
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
// 在當前section顯示多少rows。
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
// 返回每一個Cell
}
下面列出幾個大家可能不經常使用的也不需要必須實現的:
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView; // Default is 1 if not implemented
- (nullable NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section; // fixed font style. use custom view (UILabel) if you want something different
- (nullable NSString *)tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section;
2、UITableViewDelegate
的使用
UITableViewDelegate
必須實現的方法
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
// 這個方法是必須要實現的,如果此方法不是實現或者返回的CGFloat =0,其實是不執行DataSource里面的方法的
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
// 其實這個方法不是必須要實現的,但是在我們的實際工作過程中,一般都有這樣的需求,點擊cell事件。
}
TableView
還有編輯模式,在下一篇文章再作仔細的介紹。
以上就是我們TableView
最最常用的使用方式.下面介紹一些TableView
的屬性.
介紹下面幾種使用場景:
1、TableView
背景透明
當我們看到這個需求的時候,我們的第一想法是這樣的:
self.tableView.backgroundColor = [UIColor clearColor];
//或者
self.tableView.alpha = 0;
用這樣的代碼,我們看到的實際效果是,我們看不到任何內容
正確的做法:
self.tableView.backgroundColor = [UIColor colorWithWhite:0 alpha:0];
2、更改TableView
的separatorInset
在默認的TableView
樣式中,每個cell
之間有一個分割線,實際的需求中,我們可能需要取消掉這樣的分割線,或者更改分割線的inset
也就是各種間距,或者更改分割線的顏色。
去掉分割線:
self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
UITableViewCellSeparatorStyleNone
,UITableViewCellSeparatorStyleSingleLine
,UITableViewCellSeparatorStyleSingleLineEtched
三種分割線的樣式
更改分割線的Inset
:
self.tableView.separatorInset = UIEdgeInsetsMake(0, CCWH(72), 0, CCWH(16));
更改分割線的顏色:
self.tableView.separatorColor = [UIColor redcolor];
3、TableView
的headerview
在TableView
中分兩種headerview
,其一是tableview
本身的headerview
,其二是section headerview
,兩者之間有什么區別呢?
慢慢細細道來:
tableview
的headerview
是回隨著tableview
的滾動而滾動的,會滾動出屏幕的,看實現代碼
// 此處不是真實代碼
self.tableView.tableHeaderView = UIView();
section
的headerview
會隨著屏幕滾動,固定到屏幕頂部
實現只需要實現tableview
的delegate
就可以了
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{}
4、TableView
的footerView
tableview
的footerview
和headerview
,其實是一樣的。都有兩種,其一tableview
本身的footerview
,其二是section footerview
區別:tablevew
的footerview
是會滾出屏幕的,section
的footerview
會固定到底部
代碼:
// TableView footerView
self.tableView.tableFooterView = UIView();
// TableView section footerView
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{}
5、 當Tableview頁面出現鍵盤后,滑動隱藏鍵盤
直接上代碼
- (void)scrollViewWillBeginDragging:(UITableView *)scrollView {
[self.view endEditing:YES];
}
重要的代碼[self.view endEditing:YES];