點擊UITableView的cell展開收縮

首先要理解UITableView代理方法調用的先後順序。

當初始化UITableView後,代理回調順序如下

1://返回cell個數

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


2://返回每行的高度

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


3://請求數據元代理爲tableView插入需要的cell

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


4://監聽點擊的cell

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath


需要聲明一個全局BOOL變量isOpen,記錄當前cell的狀態,聲明一個NSInterge類型selectedIndex,記錄選擇的cell的row。


在heightForRowAtIndexPath代理裏面實現//選中狀態返回的高度


if (indexPath.row == selectedIndex.row && selectedIndex != nil ) {

if (isOpen == YES) {

//cell上的label高度自適應

CGSize size = [textStr sizeWithFont:[UIFont systemFontOfSize:14] constrainedToSize:CGSizeMake(290, 1000) lineBreakMode:NSLineBreakByWordWrapping];

CGFloat f = size.height;

if (indexPath.row == [self.dataArr count]-1){

return 153.8+(f - 21);

}

return 155+(f - 21);

}else{

return 67;

}

}

同樣在- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath裏實現一樣的條件

if (indexPath.row == selectedIndex.row && selectedIndex != nil) {

//如果是展開

if (isOpen == YES) {

//xxxxxx

}else{

//收起

}

//不是自身

} else {

}

當點擊時候在- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{

//將索引加到數組中

NSArray *indexPaths = [NSArray arrayWithObject:indexPath];

//判斷選中不同row狀態時候

// if (self.selectedIndex != nil && indexPath.row != selectedIndex.row) {

if (self.selectedIndex != nil && indexPath.row == selectedIndex.row) {

//將選中的和所有索引都加進數組中

// indexPaths = [NSArray arrayWithObjects:indexPath,selectedIndex, nil];

isOpen = !isOpen;

}else if (self.selectedIndex != nil && indexPath.row != selectedIndex.row) {

indexPaths = [NSArray arrayWithObjects:indexPath,selectedIndex, nil];

isOpen = YES;

}

//記下選中的索引

self.selectedIndex = indexPath;

//刷新

[tableView reloadRowsAtIndexPaths:indexPaths withRowAnimation:UITableViewRowAnimationFade];

}

經過不斷調試,終於實現了點擊任意一個cell展開收縮效果


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