I add a datetime label on the right of a table cell. When swip-to-delete shows the "Delete" button, the datetime label need to shift left a little bit. But how to get the "Delete" button's size?
I tried to find it in the cell.subviews but failed.
I add a datetime label on the right of a table cell. When swip-to-delete shows the "Delete" button, the datetime label need to shift left a little bit. But how to get the "Delete" button's size?
I tried to find it in the cell.subviews but failed.
You don't have to know the button's size. Instead, use the size of the cell's contentView
property to calculate the sizes of the subviews. When swiping over a cell, UIKit will adapt the contentView
's size and call layoutSubviews
on the cell-object. In your subclass of UITableViewCell, overwrite the layoutSubviews
method and set the appropriate sizes to the subviews.
Look at RecipeTableViewCell.m of Apple's iPhoneCoreDataRecipes sample code.
Use this code in your custom Cell class
- (void)layoutSubviews {
[super layoutSubviews];
NSMutableArray *subviews = [self.subviews mutableCopy];
while (subviews.count > 0)
{
UIView *subV = subviews[0];
[subviews removeObjectAtIndex:0];
if ([NSStringFromClass([subV class])isEqualToString:@"UITableViewCellDeleteConfirmationView"])
{
UIView *deleteButtonView = (UIView *)[self.subviews objectAtIndex:0];
CGFloat deleteBtnHeight=deleteButtonView.frame.size.height;//here you get the height
}
}
}
The size adjusts to fit the text contained. See the following code:
- (NSString *)tableView:(UITableView *)tableView
titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath
{
return @"Dynamic width!";
}
vs
- (NSString *)tableView:(UITableView *)tableView
titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath
{
return @"⏎";
}
If you don't override layoutSubviews method in your custom table view cell than my approach is:
autoresizingMask
to UIViewAutoresizingFlexibleWidth
.Now when you swipe on cell the delete button appears and your view auto resizes with contentView.