TableView系列--知識點(diǎn)

TableViewCell知識重點(diǎn)

每個TableViewCell里帶一個contentView,cell的textLabel和imageView都是加載在contentView里的,所以以后要在cell上添加控件最好在contentView上添加,以免不必要的錯誤。

contentView.png

創(chuàng)建自定義TableViewCell

  1. 首先調(diào)用cellForRowAtIndexPath方法,如果是加載nib可以在ViewDidLoad中先注冊nib文件的cell:
UINib * nib = [UINib nibWithNibName:NSStringFromClass([MZTableViewCell class])  bundle:nil];
       [self.tableView registerNib:nib forCellReuseIdentifier:@"mzCellNib"];
  1. 然后從緩存池里查找
static NSString *reuseID = @"mzCellNib";
  MZTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseID];
  1. 如果storyboard中有cell的話,設(shè)置storyboard中cell的重用標(biāo)識,在緩存池中也能找到:
storyboard設(shè)置cell.png
  1. 如果緩存池沒有,storyboard里面也木有這樣標(biāo)識的cell的話就有兩種方式來創(chuàng)建:

4.1 創(chuàng)建一個繼承自UITableViewCell的子類,比MZTableViewCell

if (cell == nil) {
    cell = [[MZTableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:reuseID];
}

4.2 也可以自己創(chuàng)建cell:從Nib里加載cell

if (cell == nil) {
 //加載xib文件加載cell,方法放回的是一個數(shù)組,取最后一個對象 
 cell = [[[NSBundle mainBundle loadNibNamed:NSStringFromClass([MZTableViewCell class]) owner:nil options:nil] lastObject];
}

注 如果nib,storyboard和.m文件中同時存在自定義的cell的話,需要注意cell的重用標(biāo)識和代碼的執(zhí)行順序,這里貼一張UIView的生命周期:

viewLifeCycle.png

TableViewController注意點(diǎn)

  • TableViewController中自帶了一個tableView,繼承了代理和數(shù)據(jù)源協(xié)議。其中的self.viewself.tableView都指的是所自帶的tableView。

  • TableViewController還有一個UIRefreshControl,可以用來實(shí)現(xiàn)下拉刷新的效果。

  • UIRefreshControl使用非常簡單,但是必須是在UITableViewController子類使用,而不能在UIViewController子類中使用。例如CustomViewController繼承自UIViewController,那么就不能使用UIRefreshControl。

  • UIRefreshControl使用很簡單,如下代碼,RootTableViewController繼承自UITableViewController,

//RootTaleiewController.h 
@interface RootTableViewController:UITableViewController
{
}
@end
//RootTableViewController.m file
@interface RootTableViewController()
 
@end
@implementation RootTableViewController
//省略不相干代碼
 
- (void)viewDidLoad
{
    [super viewDidLoad];
    //初始化UIRefreshControl
    UIRefreshControl *refreshControl = [[UIRefreshControl alloc] init];
    [refreshControl addTarget:self action:@selector(refresh:) forControlEvents:UIControlEventValueChanged];
    [self setRefreshControl:refreshControl];
}

解釋一下下面的代碼:

當(dāng)用戶向下下拉刷新的時候,refresh觸發(fā),這時候請求url鏈接中的內(nèi)容。這里使用AFNetworking來解析,代碼塊中的內(nèi)容就是解析成功之后,設(shè)置數(shù)據(jù)源self.tweets中的內(nèi)容,然后刷新UITableView界面,然后向UIRefreshControl對象發(fā)送endRefreshing消息,停止UIRefreshControl的動畫效果。如果失敗的話,也要停止UIRefreshControl的動畫效果。

- (void)refresh:(id)sender
{
    NSURL *url = [NSURL URLWithString:@"http://search.twitter.com/search.json?q=ios%20development&rpp=100&include_entities=true&result_type=mixed/"];
    // Initialize URL Request
    NSURLRequest *urlRequest = [[NSURLRequest alloc] initWithURL:url];
    // JSON Request Operation
    AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:urlRequest success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
        NSArray *results = [(NSDictionary *)JSON objectForKey:@"results"];
        if ([results count]) {
            self.tweets = results;
            // Reload Table View
            [self.tableView reloadData];
            // End Refreshing
            [(UIRefreshControl *)sender endRefreshing];
        }
    } failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
        // End Refreshing
        [(UIRefreshControl *)sender endRefreshing];
    }];
    // Start Operation
    [operation start];
}
@end

UITableView重要的API

@protocol UITableViewDelegate<NSObject, UIScrollViewDelegate>
@optional
// Display customization 這里是展示cell的時候的回調(diào)
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath;
- (void)tableView:(UITableView *)tableView willDisplayHeaderView:(UIView *)view forSection:(NSInteger)section NS_AVAILABLE_IOS(6_0);
- (void)tableView:(UITableView *)tableView willDisplayFooterView:(UIView *)view forSection:(NSInteger)section NS_AVAILABLE_IOS(6_0);
- (void)tableView:(UITableView *)tableView didEndDisplayingCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath*)indexPath NS_AVAILABLE_IOS(6_0);
- (void)tableView:(UITableView *)tableView didEndDisplayingHeaderView:(UIView *)view forSection:(NSInteger)section NS_AVAILABLE_IOS(6_0);
- (void)tableView:(UITableView *)tableView didEndDisplayingFooterView:(UIView *)view forSection:(NSInteger)section NS_AVAILABLE_IOS(6_0);

設(shè)定高度(注意estimatedHeightForRowAtIndexPath方法)

// Variable height support
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath;
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section;
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section;
// Use the estimatedHeight methods to quickly calcuate guessed values which will allow for fast load times of the table.
// If these methods are implemented, the above -tableView:heightForXXX calls will be deferred until views are ready to be displayed, so more expensive logic can be placed there.
- (CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath NS_AVAILABLE_IOS(7_0);
- (CGFloat)tableView:(UITableView *)tableView estimatedHeightForHeaderInSection:(NSInteger)section NS_AVAILABLE_IOS(7_0);
- (CGFloat)tableView:(UITableView *)tableView estimatedHeightForFooterInSection:(NSInteger)section NS_AVAILABLE_IOS(7_0);

Section的頭尾

// Section header & footer information. Views are preferred over title should you decide to provide both
- (nullable UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section;   // custom view for header. will be adjusted to default or specified header height
- (nullable UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section;   // custom view for footer. will be adjusted to default or specified footer height

Selection選擇事件

// Selection
// -tableView:shouldHighlightRowAtIndexPath: is called when a touch comes down on a row. 
// Returning NO to that message halts the selection process and does not cause the currently selected row to lose its selected look while the touch is down.
- (BOOL)tableView:(UITableView *)tableView shouldHighlightRowAtIndexPath:(NSIndexPath *)indexPath NS_AVAILABLE_IOS(6_0);
- (void)tableView:(UITableView *)tableView didHighlightRowAtIndexPath:(NSIndexPath *)indexPath NS_AVAILABLE_IOS(6_0);
- (void)tableView:(UITableView *)tableView didUnhighlightRowAtIndexPath:(NSIndexPath *)indexPath NS_AVAILABLE_IOS(6_0);
// Called before the user changes the selection. Return a new indexPath, or nil, to change the proposed selection.
- (nullable NSIndexPath *)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath;
- (nullable NSIndexPath *)tableView:(UITableView *)tableView willDeselectRowAtIndexPath:(NSIndexPath *)indexPath NS_AVAILABLE_IOS(3_0);
// Called after the user changes the selection.
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath;
- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath NS_AVAILABLE_IOS(3_0);

編輯狀態(tài)

// Editing
// Allows customization of the editingStyle for a particular cell located at 'indexPath'. If not implemented, all editable cells will have UITableViewCellEditingStyleDelete set for them when the table has editing property set to YES.
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath;
- (nullable NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath NS_AVAILABLE_IOS(3_0) __TVOS_PROHIBITED;
- (nullable NSArray<UITableViewRowAction *> *)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath NS_AVAILABLE_IOS(8_0) __TVOS_PROHIBITED; // supercedes -tableView:titleForDeleteConfirmationButtonForRowAtIndexPath: if return value is non-nil
// Controls whether the background is indented while editing.  If not implemented, the default is YES.  This is unrelated to the indentation level below.  This method only applies to grouped style table views.
- (BOOL)tableView:(UITableView *)tableView shouldIndentWhileEditingRowAtIndexPath:(NSIndexPath *)indexPath;
// The willBegin/didEnd methods are called whenever the 'editing' property is automatically changed by the table (allowing insert/delete/move). This is done by a swipe activating a single row
- (void)tableView:(UITableView*)tableView willBeginEditingRowAtIndexPath:(NSIndexPath *)indexPath __TVOS_PROHIBITED;
- (void)tableView:(UITableView*)tableView didEndEditingRowAtIndexPath:(NSIndexPath *)indexPath __TVOS_PROHIBITED;
Calling sequence for reordering a row in a table view.png

上圖中當(dāng)tableView進(jìn)入到edit模式的時候,tableView會去對當(dāng)前可見的cell逐個調(diào)用dataSource的tableView:canMoveRowAtIndexPath:方法(此處官方給出的流程圖有點(diǎn)兒問題),決定當(dāng)前cell是否顯示recordering控件,當(dāng)開始進(jìn)入拖動cell進(jìn)行拖動的時候,每滑動過一個cell的時候,會去調(diào)用delegate的tableView:targetIndexPathForMoveFromRowAtIndexPath:toProposedIndexPath:方法,去判斷當(dāng)前劃過的cell位置是否可以被替換,如果不行則給出建議的位置。當(dāng)用戶放手時本次reordering操作結(jié)束,調(diào)用dataSource中的tableView:moveRowAtIndexPath:toIndexPath:方法更新tableView對應(yīng)的數(shù)據(jù)。

當(dāng)tableView進(jìn)入編輯模式以后,cell上面顯示的delete還是insert除了跟cell的editStyle有關(guān),還與 tableView的delegate的tableView:editingStyleForRowAtIndexPath:方法的返回值有關(guān)(在這里嘮叨一句,其實(shí)delegate提供了很多改變cell屬性的機(jī)會,如非必要,還是不要去實(shí)現(xiàn)這些方法,因?yàn)閳?zhí)行這些方法也造成一定的開銷)。

delete和insert的流程如下蘋果官方文檔中給出的圖所示:

Calling_sequence_for_inserting_or_deleting_rows_in_a_table_view.png

定義長按cell的copy和paste

  // Copy/Paste.  All three methods must be implemented by the delegate.
- (BOOL)tableView:(UITableView *)tableView shouldShowMenuForRowAtIndexPath:(NSIndexPath *)indexPath NS_AVAILABLE_IOS(5_0);
- (BOOL)tableView:(UITableView *)tableView canPerformAction:(SEL)action forRowAtIndexPath:(NSIndexPath *)indexPath withSender:(nullable id)sender NS_AVAILABLE_IOS(5_0);
- (void)tableView:(UITableView *)tableView performAction:(SEL)action forRowAtIndexPath:(NSIndexPath *)indexPath withSender:(nullable id)sender NS_AVAILABLE_IOS(5_0);

設(shè)定cell的焦點(diǎn)

使用Apple TV遙控器控制屏幕上的用戶界面 = =

// Focus
- (BOOL)tableView:(UITableView *)tableView canFocusRowAtIndexPath:(NSIndexPath *)indexPath NS_AVAILABLE_IOS(9_0);
- (BOOL)tableView:(UITableView *)tableView shouldUpdateFocusInContext:(UITableViewFocusUpdateContext *)context NS_AVAILABLE_IOS(9_0);
- (void)tableView:(UITableView *)tableView didUpdateFocusInContext:(UITableViewFocusUpdateContext *)context withAnimationCoordinator:(UIFocusAnimationCoordinator *)coordinator NS_AVAILABLE_IOS(9_0);
- (nullable NSIndexPath *)indexPathForPreferredFocusedViewInTableView:(UITableView *)tableView NS_AVAILABLE_IOS(9_0);

Data刷新 (刷新可見行,visibleCell,基于cell重用機(jī)制)

// Data
- (void)reloadData; // reloads everything from scratch. redisplays visible rows. because we only keep info about visible rows, this is cheap. will adjust offset if table shrinks
- (void)reloadSectionIndexTitles NS_AVAILABLE_IOS(3_0);   // reloads the index bar.

行所對應(yīng)的視圖關(guān)系和坐標(biāo)

@property (nonatomic, readonly) NSInteger numberOfSections;
- (NSInteger)numberOfRowsInSection:(NSInteger)section;
- (CGRect)rectForSection:(NSInteger)section;                                    // includes header, footer and all rows
- (CGRect)rectForHeaderInSection:(NSInteger)section;
- (CGRect)rectForFooterInSection:(NSInteger)section;
- (CGRect)rectForRowAtIndexPath:(NSIndexPath *)indexPath;
- (nullable NSIndexPath *)indexPathForRowAtPoint:(CGPoint)point;                         // returns nil if point is outside of any row in the table
- (nullable NSIndexPath *)indexPathForCell:(UITableViewCell *)cell;                      // returns nil if cell is not visible
- (nullable NSArray<NSIndexPath *> *)indexPathsForRowsInRect:(CGRect)rect;                              // returns nil if rect not valid
- (nullable __kindof UITableViewCell *)cellForRowAtIndexPath:(NSIndexPath *)indexPath;   // returns nil if cell is not visible or index path is out of range
@property (nonatomic, readonly) NSArray<__kindof UITableViewCell *> *visibleCells;
@property (nonatomic, readonly, nullable) NSArray<NSIndexPath *> *indexPathsForVisibleRows;
- (nullable UITableViewHeaderFooterView *)headerViewForSection:(NSInteger)section NS_AVAILABLE_IOS(6_0);
- (nullable UITableViewHeaderFooterView *)footerViewForSection:(NSInteger)section NS_AVAILABLE_IOS(6_0);

滾動列表到某一行或者臨近行

- (void)scrollToRowAtIndexPath:(NSIndexPath *)indexPath atScrollPosition:(UITableViewScrollPosition)scrollPosition animated:(BOOL)animated;
- (void)scrollToNearestSelectedRowAtScrollPosition:(UITableViewScrollPosition)scrollPosition animated:(BOOL)animated;

行的插入、刪除、刷新

// Row insertion/deletion/reloading.
- (void)beginUpdates;   // allow multiple insert/delete of rows and sections to be animated simultaneously. Nestable
- (void)endUpdates;     // only call insert/delete/reload calls or change the editing state inside an update block.  otherwise things like row count, etc. may be invalid.
- (void)insertSections:(NSIndexSet *)sections withRowAnimation:(UITableViewRowAnimation)animation;
- (void)deleteSections:(NSIndexSet *)sections withRowAnimation:(UITableViewRowAnimation)animation;
- (void)reloadSections:(NSIndexSet *)sections withRowAnimation:(UITableViewRowAnimation)animation NS_AVAILABLE_IOS(3_0);
- (void)moveSection:(NSInteger)section toSection:(NSInteger)newSection NS_AVAILABLE_IOS(5_0);
- (void)insertRowsAtIndexPaths:(NSArray<NSIndexPath *> *)indexPaths withRowAnimation:(UITableViewRowAnimation)animation;
- (void)deleteRowsAtIndexPaths:(NSArray<NSIndexPath *> *)indexPaths withRowAnimation:(UITableViewRowAnimation)animation;
- (void)reloadRowsAtIndexPaths:(NSArray<NSIndexPath *> *)indexPaths withRowAnimation:(UITableViewRowAnimation)animation NS_AVAILABLE_IOS(3_0);
- (void)moveRowAtIndexPath:(NSIndexPath *)indexPath toIndexPath:(NSIndexPath *)newIndexPath NS_AVAILABLE_IOS(5_0);

UITableView的一些特性總結(jié)

一、屬性

  • dataSource —設(shè)置UITableViewDataSource的代理
  • delegate —設(shè)置UItableViewDelegate的代理
/*當(dāng)header、footer、cell的高度是固定值的話,用該方法直接設(shè)置表的高度,無需調(diào)用表的delegate方法設(shè)置它們的高度 eg:_table.rowHeight = 60 */  
/*sectionHeaderHeight、sectionFooterHeight、rowHeight -- 設(shè)置表頭、尾、cell的高度
sectionIndexColor -- 設(shè)置sectionIndexTitle(表索引子母)的顏色 */

@property (nonatomic) NSInteger sectionIndexMinimumDisplayRowCount;                                                      // show special section index list on right when row count reaches this value. default is 0  
@property (nonatomic, strong, nullable) UIColor *sectionIndexColor NS_AVAILABLE_IOS(6_0) UI_APPEARANCE_SELECTOR;                   // color used for text of the section index  
@property (nonatomic, strong, nullable) UIColor *sectionIndexBackgroundColor NS_AVAILABLE_IOS(7_0) UI_APPEARANCE_SELECTOR;         // the background color of the section index while not being touched  
@property (nonatomic, strong, nullable) UIColor *sectionIndexTrackingBackgroundColor NS_AVAILABLE_IOS(6_0) UI_APPEARANCE_SELECTOR; // the background color of the section index while it is being touched  
估算元素的高度 // NS_AVAILABLE_IOS(7_0)
[objc] view plain copy
/* 
   連接文章 介紹了estimatedRowHeight的用的場景。(適用動態(tài)的cell.height的適配) 
*/  
理解iOS 8中的Self Sizing Cells和Dynamic Type
estimatedRowHeight   ---  設(shè)置表格行的估算高度以改善性能
estimatedSectionHeaderHeight、estimatedSectionFooterHeight   -----  設(shè)置Section頭和Section尾估算高度以改善性能

- (CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath NS_AVAILABLE_IOS(7_0);  
- (CGFloat)tableView:(UITableView *)tableView estimatedHeightForHeaderInSection:(NSInteger)section NS_AVAILABLE_IOS(7_0);  
- (CGFloat)tableView:(UITableView *)tableView estimatedHeightForFooterInSection:(NSInteger)section NS_AVAILABLE_IOS(7_0);  
separatorEffect  -------- 表的分割線(毛玻璃效果)//默認(rèn)的分割線的色調(diào)暗

效果圖:


image
UIImageView *backImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"4.jpg"]]; 
    self.myTableView.backgroundView = backImageView; 
    UIBlurEffect *blureffect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleDark]; 
    UIVibrancyEffect *vinb = [UIVibrancyEffect effectForBlurEffect:blureffect]; 
    self.myTableView.separatorEffect = vinb; 
    //cell.backgroundColor = [UIColor clearColor];

二、方法

初始化方法:
  • initWithFrame:———–設(shè)置表的大小和位置
  • initWithFrame:style———設(shè)置表的大小,位置和樣式(組,單一)
  • setEditing:———-表格進(jìn)入編輯狀態(tài),無動畫
  • setEditing: animated:———表格進(jìn)入編輯狀態(tài),有動畫
  • reloadData—————刷新整個表視圖
  • reloadSectionIndexTitles——–刷新索引欄
  • numberOfSections———–獲取當(dāng)前所有的組
  • numberOfRowsInSection:———獲取某個組有多少行
  • rectForSection:———-獲取某個組的位置和大小
  • rectForHeaderInSection:———獲取某個組的頭標(biāo)簽的位置和大小
  • rectForFooterInSection:———–獲取某個組的尾標(biāo)簽的位置和大小
  • rectForRowAtIndex:———–獲取某一行的位置和大小
  • indexPathForRowAtPoint————-點(diǎn)擊某一個點(diǎn),判斷是在哪一行上的信息。
  • indexPathForCell:————獲取單元格的信息
  • indexPathsForRowsInRect:———在某個區(qū)域里會返回多個單元格信息
  • cellForRowAtIndexPath:————-通過單元格路徑得到單元格
  • visibleCells———–返回所有可見的單元格
  • indexPathsForVisibleRows——–返回所有可見行的路徑
  • headerViewForSection:——–設(shè)置頭標(biāo)簽的視圖
  • footerViewForSection;———-設(shè)置尾標(biāo)簽的視圖
  • UITableViewHeaderFooterView的使用說明
- (nullable UITableViewHeaderFooterView *)headerViewForSection:(NSInteger)section NS_AVAILABLE_IOS(6_0);  
- (nullable UITableViewHeaderFooterView *)footerViewForSection:(NSInteger)section NS_AVAILABLE_IOS(6_0);
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section  
{  
    static NSString *HeaderIdentifier = @"header";  
    //表頭、尾UITableViewHeaderFooterView的重用機(jī)制  
    //CustomHeaderView *myHeader = [tableView dequeueReusableHeaderFooterViewWithIdentifier:HeaderIdentifier];  
    if(!myHeader) {  
    //    [tableView registerClass:[CustomHeaderView class] forHeaderFooterViewReuseIdentifier:HeaderIdentifier];  
        myHeader = [[[NSBundle mainBundle] loadNibNamed:@"CustomHeaderView"  
                                                  owner:self  
                                                options:nil] objectAtIndex:0];  
    }  
  
    [myHeader.btnSomething setTitle:@"-" forState:UIControlStateNormal];  
    [myHeader.lblSomething setText:[NSString stringWithFormat:@"Section: %d",section]];  
  
    return myHeader;  
}  
  
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath  
{  
    CustomHeaderView *theHeaderView = (CustomHeaderView*)[tableView <span style="color:#FF0000;">headerViewForSection</span>:indexPath.section];  
    NSLog(@"%@",theHeaderView);  
  
    [theHeaderView.lblSomething setAlpha:theHeaderView.lblSomething.alpha-0.1];  
    [theHeaderView.btnSomething setTitle:@"+" forState:UIControlStateNormal];  
}

重用機(jī)制(2個)

dequeueReusableCellWithI dentifier:——— 獲取重用隊(duì)列里的cell單元格

/**< 使用這個方法之前必須是使用了registerNib:forCellReuseIdentifier:<span>或者</span>registerClass:forCellReuseIdentifier:方法注冊了Cell 
*/  
dequeueReusableHeaderFooterViewWithIdentifier   -------獲取重用隊(duì)列里的UITableViewHeaderFooterView的單元格

注冊一個包含指定標(biāo)示符的cell or haderFooterView 的nib對象/類

- (void)registerNib:(nullable UINib *)nib forCellReuseIdentifier:(NSString *)identifier NS_AVAILABLE_IOS(5_0);  
- (void)registerClass:(nullable Class)cellClass forCellReuseIdentifier:(NSString *)identifier NS_AVAILABLE_IOS(6_0);

- (void)registerNib:(nullable UINib *)nib forHeaderFooterViewReuseIdentifier:(NSString *)identifier NS_AVAILABLE_IOS(6_0);  
- (void)registerClass:(nullable Class)aClass forHeaderFooterViewReuseIdentifier:(NSString *)identifier NS_AVAILABLE_IOS(6_0);

beginUpdatesendUpdates兩個方法,是配合起來使用的,標(biāo)記了一個tableView的動畫塊。分別代表動畫的開始開始和結(jié)束。兩者成對出現(xiàn),可以嵌套使用。
一般,在添加,刪除,選擇 tableView中使用,并實(shí)現(xiàn)動畫效果。在動畫塊內(nèi),不建議使用reloadData方法,如果使用,會影響動畫。

調(diào)用范例

  • beginUpdates--------只添加或刪除才會更新行數(shù)
  • endUpdates---------添加或刪除后會調(diào)用添加或刪除方法時才會更新
  • insertSections:withRowAnimation:-----------插入一個或多個組,并使用動畫
  • insertRowsIndexPaths:withRowAnimation:-------插入一個或多個單元格,并使用動畫
  • deleteSections:withRowAnimation:--------刪除一個或多個組,并使用動畫
  • deleteRowIndexPaths:withRowAnimation:--------刪除一個或多個單元格,并使用動畫
  • reloadSections:withRowAnimation:---------更新一個或多個組,并使用動畫
  • reloadRowIndexPaths:withRowAnimation:-------------更新一個或多個單元格,并使用動畫
  • moveSection:toSection:-------------移動某個組到目標(biāo)組位置
  • moveRowAtIndexPath:toIndexPath:-----------移動個某個單元格到目標(biāo)單元格位置
  • indexPathsForSelectedRow----------返回選擇的一個單元格的路徑
  • indexPathsForSelectedRows---------返回選擇的所有的單元格的路徑
  • selectRowAtIndexPath:animation:scrollPosition---------設(shè)置選中某個區(qū)域內(nèi)的單元格
  • deselectRowAtIndexPath:animation:----------取消選中的單元格

UITableViewDataSource代理方法:

  • numberOfSectionsInTableView:------------設(shè)置表格的組數(shù)
  • tableView:numberOfRowInSection:----------設(shè)置每個組有多少行
  • tableView:cellForRowAtIndexPath:---------設(shè)置單元格顯示的內(nèi)容
  • tableView:titleForHeaderInSection:---------設(shè)置組表的頭標(biāo)簽視圖
  • tableView:titleForFooterInSection:-----------設(shè)置組表的尾標(biāo)簽視圖
  • tableView:canEditRowAtIndexPath:---------設(shè)置單元格是否可以編輯
  • tableView:canMoveRowAtIndexPath:--------設(shè)置單元格是否可以移動
  • tableView:sectionIndexTitleForTableView:atIndex:-------設(shè)置指定組的表的頭標(biāo)簽文本
  • tableView:commitEditingStyle:forRowAtIndexPath:----------編輯單元格(添加,刪除)
  • tableView:moveRowAtIndexPath:toIndexPath ------- 單元格移動
  • tableView:indentationLevelForRowAtIndexPath ——- 返回行層次的深度
image
/* 
- (NSInteger)tableView:(UITableView *)tableView indentationLevelForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    return [indexPath row]; 
} 
*/  
//NS_AVAILABLE_IOS(8_0)
  • tableView:editActionsForRowAtIndexPath ----- 自定義左滑動的編輯功能樣式(UITableViewRowAction)
  • tableView:titleForDeleteConfirmationButtonForRowAtIndexPath ------ 改變默認(rèn)左滑動出現(xiàn)的字樣
image
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath 
{    return YES; 
} 
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath 
{    return UITableViewCellEditingStyleDelete; 
} 
-(NSArray *)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath{ 
    UITableViewRowAction *layTopRowAction1 = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDestructive title:@"刪除" handler:^(UITableViewRowAction *action, NSIndexPath *indexPath) { 
        NSLog(@"點(diǎn)擊了刪除"); 
        [tableView setEditing:NO animated:YES]; 
    }]; 
    layTopRowAction1.backgroundColor = [UIColor redColor]; 
    UITableViewRowAction *layTopRowAction2 = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDestructive title:@"置頂" handler:^(UITableViewRowAction *action, NSIndexPath *indexPath) { 
        NSLog(@"點(diǎn)擊了置頂"); 
        [tableView setEditing:NO animated:YES]; 
    }]; 
    layTopRowAction2.backgroundColor = [UIColor greenColor]; 
    UITableViewRowAction *layTopRowAction3 = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDestructive title:@"更多" handler:^(UITableViewRowAction *action, NSIndexPath *indexPath) { 
        NSLog(@"點(diǎn)擊了更多"); 
        [tableView setEditing:NO animated:YES]; 
         
    }]; 
    layTopRowAction3.backgroundColor = [UIColor blueColor]; 
    NSArray *arr = @[layTopRowAction1,layTopRowAction2,layTopRowAction3]; 
    return arr; 
}

UITableViewDelegate代理方法: (iOS8以上)

tableView:willDisplayFooterView:forSection:tableView:willDisplayHeaderView:forSection:可以正常被調(diào)用
在iOS7(iOS6沒測試)上卻沒有被調(diào)用
原來iOS7必須同時實(shí)現(xiàn)了Header和Footer這個delegate才會被調(diào)用所以

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section  
{  
    return 0.f;  
}  
   
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section  
{  
    UIView *view = [UIView new];  
    view.backgroundColor = [UIColor clearColor];  
    return view;  
}  
  • tableView: willDisplayHeaderView: forSection: -------- 設(shè)置當(dāng)前section頭的樣式
  • tableView: willDisplayCell:forRowAtIndexPath:-----------設(shè)置當(dāng)前的單元格


    image
-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    cell.transform = CGAffineTransformMakeTranslation(320, 0); 
    [UIView animateWithDuration:indexPath.row*0.2 animations:^{ 
        cell.transform = CGAffineTransformIdentity; 
    }]; 
}
  • tableView: heightForRowAtIndexPath:-----------設(shè)置每行的高度
  • tableView:tableViewheightForHeaderInSection:-----------設(shè)置組表的頭標(biāo)簽高度
  • tableView:tableViewheightForFooterInSection:-------------設(shè)置組表的尾標(biāo)簽高度
  • tableView: viewForHeaderInSection:----------自定義組表的頭標(biāo)簽視圖
  • tableView: viewForFooterInSection: ----------自定義組表的尾標(biāo)簽視圖
  • tableView:accessoryButtonTappedForRowWithIndexPath:-----------設(shè)置某個單元格上的右指向按鈕的響應(yīng)方法
image
    UIImage *image= [ UIImage imageNamed:@"man" ];  
    UIButton *button = [ UIButton buttonWithType:UIButtonTypeCustom ];  
    CGRect frame = CGRectMake( 0.0 , 0.0 , image.size.width , image.size.height );  
    button.frame = frame;  
    [button setBackgroundImage:image forState:UIControlStateNormal ];  
    button.backgroundColor = [UIColor clearColor ];  
    [button addTarget:self  
               action:@selector(accessoryButtonIsTapped:event:) forControlEvents:UIControlEventTouchUpInside];  
  
- (void)accessoryButtonIsTapped:(id)sender event:(id)event{  
    NSSet *touches = [event allTouches];  
    UITouch *touch = [touches anyObject];  
    CGPoint currentTouchPosition = [touch locationInView:self.tableView];  
    NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:currentTouchPosition];  
    if(indexPath != nil)  
    {  
        [self tableView:self.tableView accessoryButtonTappedForRowWithIndexPath:indexPath];  
    }  
}
  • tableView:willSelectRowAtIndexPath:-----------獲取將要選擇的單元格的路徑
  • tableView:didSelectRowAtIndexPath:-----------獲取選中的單元格的響應(yīng)事件
  • tableView: tableViewwillDeselectRowAtIndexPath:------------獲取將要未選中的單元格的路徑
  • tableView:didDeselectRowAtIndexPath:-----------獲取未選中的單元格響應(yīng)事件NS_AVAILABLE_IOS(9_0)
  • remembersLastFocusedIndexPath -------- 使用Apple TV遙控器控制屏幕上的用戶界面
- (BOOL)tableView:(UITableView *)tableView canFocusRowAtIndexPath:(NSIndexPath *)indexPath NS_AVAILABLE_IOS(9_0);  
- (BOOL)tableView:(UITableView *)tableView shouldUpdateFocusInContext:(UITableViewFocusUpdateContext *)context NS_AVAILABLE_IOS(9_0);  
- (void)tableView:(UITableView *)tableView didUpdateFocusInContext:(UITableViewFocusUpdateContext *)context withAnimationCoordinator:(UIFocusAnimationCoordinator *)coordinator NS_AVAILABLE_IOS(9_0);  
- (nullable NSIndexPath *)indexPathForPreferredFocusedViewInTableView:(UITableView *)tableView NS_AVAILABLE_IOS(9_0);  
  • cellLayoutMarginsFollowReadableWidth ------- 判斷是否需要根據(jù)內(nèi)容留有空白

參考博文

  1. UITableView學(xué)習(xí)筆記
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容