sách gpt4 ai đã đi

ios - 在选择器中传递参数(UIMenuController)

In lại 作者:行者123 更新时间:2023-12-01 18:05:04 27 4
mua khóa gpt4 Nike

Tôi có một cái UIMenuController在 Collection View 单元格顶部有一个“删除”菜单项,当用户长按第 1 节的单元格时显示该菜单项:

nhập mô tả hình ảnh ở đây

@IBAction func handleLongPressOnCell(_ sender: UILongPressGestureRecognizer) {
let p = sender.location(in: collectionView)
guard sender.state == .began, let indexPath = self.collectionView.indexPathForItem(at: p), let cell = self.collectionView.cellForItem(at: indexPath) else { return }

if indexPath.section == 1 {
let frameInSuperView = collectionView.convert(cell.frame, to: view)
let deleteItem = UIMenuItem(title: "Delete", action: #selector(deleteCell))
UIMenuController.shared.menuItems = [deleteItem]
UIMenuController.shared.setTargetRect(frameInSuperView, in: view)
becomeFirstResponder()
UIMenuController.shared.setMenuVisible(true, animated: true)
}
}

如何将单元格的索引路径传递给下面的函数?我需要这些信息来从服务器中删除对象。
@objc internal func deleteCell(sender: UIMenuItem) {
print("delete menu item tapped! print index path of selected collection view cell?")
}

1 Câu trả lời

正如@mkeremkeskin 指出的那样,在他链接的地方有一个答案。但这个答案在Objective-C 中,在这里你会找到一个Swift 4 版本。

您可以将 UIMenuItem 子类化并将 indexPath 添加到它!
我必须删除一些代码才能在我的操场上工作,但你明白了:)

class CustomMenuItem: UIMenuItem {
var indexPath: IndexPath?

convenience init(title: String, action: Selector, indexPath: IndexPath? = nil) {
self.init(title: title, action: action)

self.indexPath = indexPath
}
}

class ViewController {

func handleLongPressOnCell(_ sender: UILongPressGestureRecognizer) {

let indexPath = IndexPath(item: 0, section: 1)

if indexPath.section == 1 {
let deleteItem = CustomMenuItem(title: "Delete", action: #selector(deleteCell), indexPath: indexPath)
UIMenuController.shared.menuItems = [deleteItem]
UIMenuController.shared.setMenuVisible(true, animated: true)
}
}

@objc internal func deleteCell(sender: CustomMenuItem) {
guard let indexPath = sender.indexPath else { return }

// Delete item based on indexPath
}
}

关于ios - 在选择器中传递参数(UIMenuController),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48905673/

27 4 0
行者123
Hồ sơ cá nhân

Tôi là một lập trình viên xuất sắc, rất giỏi!

Nhận phiếu giảm giá Didi Taxi miễn phí
Mã giảm giá Didi Taxi
Giấy chứng nhận ICP Bắc Kinh số 000000
Hợp tác quảng cáo: 1813099741@qq.com 6ren.com