眾所周知疑苫,在 iOS 里 UITableView 的左滑/側(cè)滑刪除的功能還是挺美觀的,最近項目的需求里就用到了這個樣式
需求圖片
當(dāng)時接到這個需求的時候也在網(wǎng)上查找了很多資料纷责,非常感謝這篇文章帶給我的靈感
iOS cell自定義左滑/側(cè)滑刪除(支持iOS11)
但iOS13 以上的系統(tǒng)左滑控件的層級以及類名都發(fā)生了變化捍掺,以前的方法明顯不夠用了,通過不斷的斷點分析再膳,類名輸出后終于正確的適配上了 iOS13挺勿,特在此記錄一下
1. 定義左滑出來的控件方法
- (NSArray<UITableViewRowAction *> *)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath {
// 這里的標(biāo)題我使用的 4 個空格進行占位
UITableViewRowAction *action = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleNormal title:@" " handler:^(UITableViewRowAction * _Nonnull action, NSIndexPath * _Nonnull indexPath) {
// 點擊刪除按鈕需要執(zhí)行的方法
[tableView setEditing:NO animated:YES];
}];
// 修改背景顏色
action.backgroundColor = hexColor(0xEB1163);
return @[action];
}
2. 監(jiān)聽即將開啟編輯狀態(tài)的事件
- (void)tableView:(UITableView *)tableView willBeginEditingRowAtIndexPath:(NSIndexPath *)indexPath {
// 在 iOS11 以下系統(tǒng),因為方法線程問題,需要放到主線程執(zhí)行, 不然沒有效果
dispatch_async(dispatch_get_main_queue(), ^{
[self setupSlideBtnWithEditingIndexPath:indexPath];
});
}
3.設(shè)置左滑出來的按鈕樣式
//MARK: 設(shè)置左滑按鈕的樣式
- (void)setupSlideBtnWithEditingIndexPath:(NSIndexPath *)editingIndexPath {
// 判斷系統(tǒng)是否是 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;
}
// 判斷系統(tǒng)是否是 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;
// 拿到按鈕,設(shè)置圖片
UIButton *button = rowActionView.subviews.firstObject;
[button setImage:kImageName(@"delete_col") forState:UIControlStateNormal];
[button setTitle:@"" forState:UIControlStateNormal];
}
到這里我們就已經(jīng)實現(xiàn)我們需要的效果了不瓶,但是在 iOS13 以上,有時候快速左滑/側(cè)滑時并不能執(zhí)行
- (void)tableView:(UITableView *)tableView willBeginEditingRowAtIndexPath:(NSIndexPath *)indexPath;
方法灾杰,所以會自定義不了按鈕蚊丐,但是輕輕滑動卻能執(zhí)行,目前不清楚是什么原因吭露,希望知道的大佬能告訴一下吠撮,謝謝。