Эффект тени при удалении строки TableCell

Я хочу добавить этот эффект тени под строкой, перемещая строку для удаления.

Эффект тени при удалении строки TableCell

Я показываю кнопку удаления здесь, в моем контроллере

     func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
        let cell = tableView.dequeueReusableCell(forIndexPath: indexPath) as NewNotificationTableViewCell
        let delete = UITableViewRowAction(style: .normal, title: "Delete") { [self] action, index in
            sectionArray[indexPath.section].items.remove(at: indexPath.row)
               tableView.deleteRows(at: [indexPath], with: UITableView.RowAnimation.automatic)

               if sectionArray[indexPath.section].items.isEmpty {
                   sectionArray.remove(at: indexPath.section)
                   cell.addShadow()
tableView.deleteSections(.init(integer: indexPath.section), with: .automatic)
               }
           }
           delete.backgroundColor = UIColor.red
           return [delete]
       }
}
Стоит ли изучать PHP в 2023-2024 годах?
Стоит ли изучать PHP в 2023-2024 годах?
Привет всем, сегодня я хочу высказать свои соображения по поводу вопроса, который я уже много раз получал в своем сообществе: "Стоит ли изучать PHP в...
Поведение ключевого слова "this" в стрелочной функции в сравнении с нормальной функцией
Поведение ключевого слова "this" в стрелочной функции в сравнении с нормальной функцией
В JavaScript одним из самых запутанных понятий является поведение ключевого слова "this" в стрелочной и обычной функциях.
Приемы CSS-макетирования - floats и Flexbox
Приемы CSS-макетирования - floats и Flexbox
Здравствуйте, друзья-студенты! Готовы совершенствовать свои навыки веб-дизайна? Сегодня в нашем путешествии мы рассмотрим приемы CSS-верстки - в...
Тестирование функциональных ngrx-эффектов в Angular 16 с помощью Jest
В системе управления состояниями ngrx, совместимой с Angular 16, появились функциональные эффекты. Это здорово и делает код определенно легче для...
Концепция локализации и ее применение в приложениях React ⚡️
Концепция локализации и ее применение в приложениях React ⚡️
Локализация - это процесс адаптации приложения к различным языкам и культурным требованиям. Это позволяет пользователям получить опыт, соответствующий...
Пользовательский скаляр GraphQL
Пользовательский скаляр GraphQL
Листовые узлы системы типов GraphQL называются скалярами. Достигнув скалярного типа, невозможно спуститься дальше по иерархии типов. Скалярный тип...
0
0
32
2
Перейти к ответу Данный вопрос помечен как решенный

Ответы 2

Думаю лучше перейти на использование UIContextualAction. Его легче настроить, чем старый и устаревший UITableViewRowAction. Обратитесь к этой статье: https://www.hackingwithswift.com/forums/ios/uitableview-swipe-actions-ios13-swift-5/2256

func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
    return UISwipeActionsConfiguration(actions: [
        makeDeleteContextualAction(forRowAt: indexPath)
    ])
}

//MARK: - Contextual Actions
private func makeDeleteContextualAction(forRowAt indexPath: IndexPath) -> UIContextualAction {
    return UIContextualAction(style: .destructive, title: "Delete") { (action, swipeButtonView, completion) in
        print("DELETE HERE")
        action.image = ProjectImages.Annotation.checkmark
        action.image?.withTintColor(.systemGreen)
        action.backgroundColor = .systemOrange
//==> Put your shadow code here
        completion(true)
    }
}

мой проект поддерживает iOS 10, поэтому этот метод будет работать для iOS 11 и выше.

Mert Köksal 23.03.2022 09:20

Понятно, как насчет использования внешней библиотеки, такой как github.com/SwipeCellKit/SwipeCellKit. Думаю, есть способ настроить действие

Quang Hà 23.03.2022 09:23

мой код может прокручивать, показывать удаление и удаление. Единственная проблема в том, что я не мог понять, как показать тень во время этого смахивания.

Mert Köksal 23.03.2022 09:31

Я понимаю, я имею в виду настроить управление по умолчанию, иногда это сложнее, чем использовать внешнюю библиотеку

Quang Hà 23.03.2022 14:01
Ответ принят как подходящий

Использование SwipeKit решило мою проблему с тенью с помощью приведенного ниже кода.

extension NewNotificationViewController: SwipeTableViewCellDelegate {

func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath, for orientation: SwipeActionsOrientation) -> [SwipeAction]? {
    if orientation == .right {
        let currentCell = tableView.cellForRow(at: indexPath)
        currentCell?.contentView.addShadow(offset: CGSize.init(width: 0, height: 1), color: KSColor.bwBlack.getColor(), radius: 4.0, opacity: 0.10)
        let delete = SwipeAction(style: .default, title: "enum.descriptor.delete".localized) { action, indexPath in
            self.sectionArray[indexPath.section].items.remove(at: indexPath.row)
            self.tableView.deleteRows(at: [indexPath], with: UITableView.RowAnimation.automatic)
            if self.sectionArray[indexPath.section].items.isEmpty {
                self.sectionArray.remove(at: indexPath.section)
                self.tableView.deleteSections(.init(integer: indexPath.section), with: .automatic)
            }
        }
        configure(action: delete, with: .delete)
        return [delete]
    } else {
        return nil
    }
}

func tableView(_ tableView: UITableView, editActionsOptionsForRowAt indexPath: IndexPath, for orientation: SwipeActionsOrientation) -> SwipeOptions {
    var options = SwipeTableOptions()
    options.expansionStyle = .destructive(automaticallyDelete: false)
    options.transitionStyle = defaultOptions.transitionStyle
    options.maximumButtonWidth = 60
    return options
}

func configure(action: SwipeAction, with descriptor: ActionDescriptor) {
    action.title = descriptor.title(forDisplayMode: buttonDisplayMode)
    action.backgroundColor = KSColor.red500Base.getColor()
}

func tableView(_ tableView: UITableView, didEndEditingRowAt indexPath: IndexPath?, for orientation: SwipeActionsOrientation) {
    let currentCell = tableView.cellForRow(at: indexPath!)
    currentCell?.contentView.addShadow(offset: CGSize.init(width: 0, height: 0), color: .clear, radius: 0.0, opacity: 0.0)
}
}

Я также изменил свой тип ячейки на

class NewNotificationTableViewCell: SwipeTableViewCell

и делегировать себя

Другие вопросы по теме