Max*_*Max 5 list swipe swift swiftui
如何在SwiftUI中使用自定义滑动动作?
我试图使用UIKit框架使它们在SwiftUI中工作。但这对我不起作用。
import SwiftUI
import UIKit
init() {
override func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
let important = importantAction(at: indexPath)
return UISwipeActionsConfiguration(actions: [important])
}
func importantAction(at indexPath: IndexPath) -> UIContextualAction {
let action = UIContextualAction(style: .normal, title: "Important") { (action, view, completion) in
print("HI")
}
action.backgroundColor = UIColor(hue: 0.0861, saturation: 0.76, brightness: 0.94, alpha: 1.0) /* #f19938 */
action.image = UIImage(named: "pencil")
return action
}
}
struct TestView: View {
NavigationView {
List {
ForEach(appointmentsViewModel.appointments.identified(by: \.id)) { appointment in Row_Appointments(appointment: appointment)
}.onDelete(perform: delete)
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
在 iOS 15 中我们终于可以使用原生的Swipe Actions了:
func swipeActions<T>(edge: HorizontalEdge = .trailing, allowsFullSwipe: Bool = true, content: () -> T) -> some View where T : View
Run Code Online (Sandbox Code Playgroud)
ForEach它们可以像onMove或 一样附加到容器上onDelete:
List {
ForEach(appointmentsViewModel.appointments.identified(by: \.id)) { appointment in
Row_Appointments(appointment: appointment)
}
.swipeActions(edge: .trailing) {
Button {
print("Hi")
} label: {
Label("Important", systemImage: "pencil")
}
}
}
Run Code Online (Sandbox Code Playgroud)
基于米夏?Ziobro使用Introspect回答以简化表视图委托设置。
请注意,这将覆盖表视图委托,并且可能会破坏一些现有的表视图行为。虽然可以通过将方法添加到自定义委托来修复诸如 header hight 之类的问题,但其他可能无法修复。
struct ListSwipeActions: ViewModifier {
@ObservedObject var coordinator = Coordinator()
func body(content: Content) -> some View {
return content
.introspectTableView { tableView in
tableView.delegate = self.coordinator
}
}
class Coordinator: NSObject, ObservableObject, UITableViewDelegate {
func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCell.EditingStyle {
return .delete
}
func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
let archiveAction = UIContextualAction(style: .normal, title: "Title") { action, view, completionHandler in
// update data source
completionHandler(true)
}
archiveAction.image = UIImage(systemName: "archivebox")!
archiveAction.backgroundColor = .systemYellow
let configuration = UISwipeActionsConfiguration(actions: [archiveAction])
return configuration
}
}
}
extension List {
func swipeActions() -> some View {
return self.modifier(ListSwipeActions())
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1308 次 |
| 最近记录: |