我希望能够在我的 UITableViewCell
中隐藏一个标签,以便在用户滑动删除单元格时阻止它与标题重叠。
我正在使用以下代码来启动和处理滑动以删除:
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
if (editingStyle == UITableViewCellEditingStyleDelete) {
[self.tableView beginUpdates]; // Avoid NSInternalInconsistencyException
// Delete the project object that was swiped
Project *projectToDelete = [self.fetchedResultsController objectAtIndexPath:indexPath];
NSLog(@"Deleting (%@)", projectToDelete.name);
[self.managedObjectContext deleteObject:projectToDelete];
[self.managedObjectContext save:nil];
// Delete the (now empty) row on the table
[self.tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationLeft];
[self performFetch];
[self.tableView endUpdates];
}
}
我使用以下方法在单元格中分配了标签:
UILabel *projectDate = (UILabel *)[cell viewWithTag:3];
projectDate.text = project.dateStarted;
并已尝试设置
projectDate.hidden = YES;
但是,这不起作用。
最佳答案
我认为您需要继承 UITableViewCell
来实现它。在子类中覆盖 - (void) setEditing:(BOOL)editing animated:(BOOL)animated
。在这种方法中,您可以隐藏标签。如果您只需要隐藏删除操作的标签,则使用 self.editingStyle
根据编辑样式(又名:UITableViewCellEditingStyleDelete)有条件地隐藏标签。
这里有两个例子。我更喜欢示例二,它更容易。但是示例 1 将让您替换文本,这可能会有用:
@implementation CellSubclass{
NSString *_labelText; //only used in example 1
}
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
if (self) {
// Initialization code
}
return self;
}
- (void)setSelected:(BOOL)selected animated:(BOOL)animated{
[super setSelected:selected animated:animated];
// Configure the view for the selected state
}
// Example 1, replacing the text value
- (void) setEditing:(BOOL)editing animated:(BOOL)animated{
[super setEditing:editing animated:animated];
if (editing && self.editingStyle == UITableViewCellEditingStyleDelete){
UILabel *label = (UILabel *)[self viewWithTag:3];
_labelText = label.text;
self.textLabel.text = nil;
} else if (!editing && _labelText){
UILabel *label = (UILabel *)[self viewWithTag:3];
label.text = _labelText;
}
}
//Example 2 - hiding the view itself
- (void) setEditing:(BOOL)editing animated:(BOOL)animated{
[super setEditing:editing animated:animated];
if (editing && self.editingStyle == UITableViewCellEditingStyleDelete){
[self viewWithTag:3].alpha = 0.0f;
} else {
[self viewWithTag:3].alpha = 1.0f;
}
}
@end
请注意,我有两个同名的方法。这显然是一个很大的禁忌......只使用其中一个。
另请注意,我忽略了动画参数。如果你想在第二个例子中让你的标签消失动画(又名......淡出/淡入)你需要做的就是围绕你的变化在一个动画 block 中,就像这样:
[UIView animateWithDuration:.3f animations:^{
[self viewWithTag:3].alpha = 0.0f;
}];
我认为您不能为第一个示例制作动画。
关于ios - 滑动删除时隐藏 UITableViewCell 中的标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9604733/