【发布时间】:2011-09-21 19:08:28
【问题描述】:
- 我在 UIView 中有一个 UITableView
- 表格视图的单元格是自定义的,因此由 UITableViewCell 类管理
我需要在选择时扩展/收缩单元格,这是我使用很棒的教程 here 完成的。但是,我还需要在选择时显示/隐藏 UILabels - 就像详细视图一样,当您展开单元格时,会显示更多标签;将其收缩回原来的大小,这些标签再次被隐藏。
基本上:
点击
延长单元格长度
显示标签
再次点击
契约细胞
隐藏标签
一次只能打开 1 个单元格
这一切听起来都很简单,但是网络上普遍使用的方法(我上面链接的教程)在第一次触摸时会自动取消选择它的单元格,这意味着我隐藏的 UILabel 永远没有机会出现。
如果我删除
[tableView deselectRowAtIndexPath:indexPath animated:TRUE];
从 didSelectRowAtIndexPath 中,我可以让隐藏标签出现,但它当然不会消失,因为在我选择不同的单元格之前,单元格不会被取消选择。
如何使单元格在用户第二次单击它后返回到其正常高度后自动取消选择?此外,有没有办法将表格一次限制为一个展开的单元格,因为现在,您可以完全展开所有单元格。如果扩展 Cell2 会自动将 Cell1 缩回到原来的高度,我会喜欢它。
谢谢大家;有时不知道如果没有 Stack Overflow 该怎么办。
TableViewController.h
@interface TableViewController : UIViewController <UITableViewDelegate, UITableViewDataSource> {
IBOutlet UITableView *tableView;
NSMutableDictionary *selectedIndexes;
}
@end
TableViewController.m 中的相关代码
@interface TableViewController (private)
- (BOOL)cellIsSelected:(NSIndexPath *)indexPath;
@end
@implementation TableViewController
#define kCellHeight 50.0
- (void)viewDidLoad {
[super viewDidLoad];
selectedIndexes = [[NSMutableDictionary alloc] init];
}
- (BOOL)cellIsSelected:(NSIndexPath *)indexPath {
// Return whether the cell at the specified index path is selected or not
NSNumber *selectedIndex = [selectedIndexes objectForKey:indexPath];
return selectedIndex == nil ? FALSE : [selectedIndex boolValue];
}
- (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];
}
return cell;
}
#pragma mark -
#pragma mark Tableview Delegate Methods
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
// Deselect cell
[tableView deselectRowAtIndexPath:indexPath animated:TRUE];
// Toggle 'selected' state
BOOL isSelected = ![self cellIsSelected:indexPath];
// Store cell 'selected' state keyed on indexPath
NSNumber *selectedIndex = [NSNumber numberWithBool:isSelected];
[selectedIndexes setObject:selectedIndex forKey:indexPath];
// This is where magic happens...
[tableView beginUpdates];
[tableView endUpdates];
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
// If our cell is selected, return double height
if([self cellIsSelected:indexPath]) {
return kCellHeight * 2.0;
}
// Cell isn't selected so return single height
return kCellHeight;
}
@end
另外,来自 UITableCell 类的 UILabels:
- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
[super setSelected:selected animated:animated];
if (selected == YES){
date.hidden = NO;
}
else if (selected == NO) {
date.hidden = YES;
}
}
【问题讨论】:
-
我正在显示,在我当前的项目中也动态隐藏单元格。我也找到了更好的方法来实现这一点。它更容易更方便:)。这两条神奇的线将更新
标签: iphone height cell show-hide expand