衆所周知,在 iOS 裏 UITableView 的左滑/側滑刪除的功能仍是挺美觀的,最近項目的需求裏就用到了這個樣式 markdown
iOS cell自定義左滑/側滑刪除(支持iOS11)async
但iOS13 以上的系統左滑控件的層級以及類名都發生了變化,之前的方法明顯不夠用了,經過不斷的斷點分析,類名輸出後終於正確的適配上了 iOS13,特在此記錄一下ide
- (NSArray<UITableViewRowAction *> *)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath {
// 這裏的標題我使用的 4 個空格進行佔位
UITableViewRowAction *action = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleNormal title:@" " handler:^(UITableViewRowAction * _Nonnull action, NSIndexPath * _Nonnull indexPath) {
// 點擊刪除按鈕須要執行的方法
[tableView setEditing:NO animated:YES];
}];
// 修改背景顏色
action.backgroundColor = hexColor(0xEB1163);
return @[action];
}
複製代碼
- (void)tableView:(UITableView *)tableView willBeginEditingRowAtIndexPath:(NSIndexPath *)indexPath {
// 在 iOS11 如下系統,由於方法線程問題,須要放到主線程執行, 否則沒有效果
dispatch_async(dispatch_get_main_queue(), ^{
[self setupSlideBtnWithEditingIndexPath:indexPath];
});
}
複製代碼
//MARK: 設置左滑按鈕的樣式
- (void)setupSlideBtnWithEditingIndexPath:(NSIndexPath *)editingIndexPath {
// 判斷系統是不是 iOS13 及以上版本
if (@available(iOS 13.0, *)) {
for (UIView *subView in self.tableView.subviews) {
if ([subView isKindOfClass:NSClassFromString(@"_UITableViewCellSwipeContainerView")] && [subView.subviews count] >= 1) {
// 修改圖片
UIView *remarkContentView = subView.subviews.firstObject;
[self setupRowActionView:remarkContentView];
}
}
return;
}
// 判斷系統是不是 iOS11 及以上版本
if (@available(iOS 11.0, *)) {
for (UIView *subView in self.tableView.subviews) {
if ([subView isKindOfClass:NSClassFromString(@"UISwipeActionPullView")] && [subView.subviews count] >= 1) {
// 修改圖片
UIView *remarkContentView = subView;
[self setupRowActionView:remarkContentView];
}
}
return;
}
// iOS11 如下的版本
MTMineCollectionTableViewCell *cell = [self.tableView cellForRowAtIndexPath:editingIndexPath];
for (UIView *subView in cell.subviews) {
if ([subView isKindOfClass:NSClassFromString(@"UITableViewCellDeleteConfirmationView")] && [subView.subviews count] >= 1) {
// 修改圖片
UIView *remarkContentView = subView;
[self setupRowActionView:remarkContentView];
}
}
}
- (void)setupRowActionView:(UIView *)rowActionView {
// 切割圓角
[rowActionView cl_setCornerAllRadiusWithRadiu:20];
// 改變父 View 的frame,這句話是由於我在 contentView 里加了另外一個 View,爲了使劃出的按鈕能與其達到同一高度
CGRect frame = rowActionView.frame;
frame.origin.y += kFitRealValue(7);
frame.size.height -= kFitRealValue(13);
rowActionView.frame = frame;
// 拿到按鈕,設置圖片
UIButton *button = rowActionView.subviews.firstObject;
[button setImage:kImageName(@"delete_col") forState:UIControlStateNormal];
[button setTitle:@"" forState:UIControlStateNormal];
}
複製代碼
到這裏咱們就已經實現咱們須要的效果了,可是在 iOS13 以上,有時候快速左滑/側滑時並不能執行oop
- (void)tableView:(UITableView *)tableView willBeginEditingRowAtIndexPath:(NSIndexPath *)indexPath;
spa
方法,因此會自定義不了按鈕,可是輕輕滑動卻能執行,目前不清楚是什麼緣由,但願知道的大佬能告訴一下,謝謝。線程