如何在UIContextMenuInteractionDelegate中的两个或多个视图中处理tap



有两个视图,并添加了UIContextMenuInteraction到两个视图。点击其中一个视图后,需要确定点击了哪个视图。

class Cell: UITableViewCell {
let redView = UIView()
let blueView = UIView()
...
func setup() {
let interaction1 = UIContextMenuInteraction(delegate: self)
redView.addInteraction(interaction)

let interaction2 = UIContextMenuInteraction(delegate: self)
blueView.addInteraction(interaction)
}
}
extension Cell: UIContextMenuInteractionDelegate {
func contextMenuInteraction(_ interaction: UIContextMenuInteraction,    configurationForMenuAtLocation location: CGPoint) -> UIContextMenuConfiguration? {
return UIContextMenuConfiguration(identifier: nil, previewProvider: nil, actionProvider:    { suggestedActions in
// How to here identify which view was tapped
// if tapped redView -> show custom menu1
// if tapped blueView -> show custom menu2
})
}
}

对于一个视图它工作得很好。但是对于两个或多个视图,很难确定是哪个视图被点击了

第一个参数-interaction- in:

func contextMenuInteraction(_ interaction: UIContextMenuInteraction, configurationForMenuAtLocation location: CGPoint) -> UIContextMenuConfiguration? {

是对UIContextMenuInteraction对象的引用。

所以,就像你有两个视图作为类属性一样,添加两个UIContextMenuInteraction变量作为属性:

class Cell: UITableViewCell {

let redView = UIView()
let blueView = UIView()
var redInteraction: UIContextMenuInteraction!
var blueInteraction: UIContextMenuInteraction!
func setup() {
redInteraction = UIContextMenuInteraction(delegate: self)
redView.addInteraction(redInteraction)

blueInteraction = UIContextMenuInteraction(delegate: self)
blueView.addInteraction(blueInteraction)
}

}

当委托被调用时,您可以评估interaction以确定哪个调用了菜单:

extension Cell: UIContextMenuInteractionDelegate {

func contextMenuInteraction(_ interaction: UIContextMenuInteraction, configurationForMenuAtLocation location: CGPoint) -> UIContextMenuConfiguration? {

if interaction == redInteraction {

// redView context menu invoked

let favorite = UIAction(title: "Red Favorite", image: UIImage(systemName: "heart.fill")) { _ in
// Perform action
}

let share = UIAction(title: "Red Share", image: UIImage(systemName: "square.and.arrow.up.fill")) { action in
// Perform action
}

let delete = UIAction(title: "Red Delete", image: UIImage(systemName: "trash.fill"), attributes: [.destructive]) { action in
// Perform action
}

return UIContextMenuConfiguration(identifier: nil, previewProvider: nil) { _ in
UIMenu(title: "Red Actions", children: [favorite, share, delete])
}
}

// blueView context menu invoked
let share = UIAction(title: "Blue Share", image: UIImage(systemName: "square.and.arrow.up.fill")) { action in
// Perform action
}

let delete = UIAction(title: "Blue Delete", image: UIImage(systemName: "trash.fill"), attributes: [.destructive]) { action in
// Perform action
}

return UIContextMenuConfiguration(identifier: nil, previewProvider: nil) { _ in
UIMenu(title: "Blue Actions", children: [share, delete])
}

}

}

最新更新