经过一些尝试,我成功地移除了模糊效果,像这样。你需要一个实用方法:
extension UIView {
func subviews<T:UIView>(ofType WhatType:T.Type,
recursing:Bool = true) -> [T] {
var result = self.subviews.compactMap {$0 as? T}
guard recursing else { return result }
for sub in self.subviews {
result.append(contentsOf: sub.subviews(ofType:WhatType))
}
return result
}
}
现在,我们使用上下文菜单交互委托方法来查找负责模糊的UIVisualEffectView并将其删除:
func contextMenuInteraction(_ interaction: UIContextMenuInteraction, willDisplayMenuFor configuration: UIContextMenuConfiguration, animator: UIContextMenuInteractionAnimating?) {
DispatchQueue.main.async {
let v = self.view.window!.subviews(ofType:UIVisualEffectView.self)
if let v = v.first {
v.alpha = 0
}
}
}
典型的结果:
![在这里输入图片描述](https://istack.dev59.com/q7UHc.webp)
不幸的是,现在菜单后面完全没有阴影了,但这比大模糊好。
当然,它仍然是一个长按手势。我怀疑对此无能为力!如果这是一个普通的UILongPressGestureRecognizer,则可能可以定位它并缩短其minimumPressDuration
,但它不是;你必须遵守UIContextMenuInteraction的规则。
然而,说了这么多,如果可能的话,我想到了一个更好的方法:让这个UIView 成为 UIControl!现在它就像一个UIControl一样行事。例如:
class MyControl : UIControl {
override func contextMenuInteraction(_ interaction: UIContextMenuInteraction, configurationForMenuAtLocation location: CGPoint) -> UIContextMenuConfiguration? {
let config = UIContextMenuConfiguration(identifier: nil, previewProvider: nil, actionProvider: { _ in
let act = UIAction(title: "Red") { action in }
let act2 = UIAction(title: "Green") { action in }
let act3 = UIAction(title: "Blue") { action in }
let men = UIMenu(children: [act, act2, act3])
return men
})
return config
}
}
并且:
let v = MyControl()
v.isContextMenuInteractionEnabled = true
v.showsMenuAsPrimaryAction = true
v.frame = CGRect(x: 100, y: 100, width: 200, height: 100)
v.backgroundColor = .red
self.view.addSubview(v)
结果就是简单地敲击屏幕即可调用菜单,长这样:
![enter image description here](https://istack.dev59.com/f40En.webp)
如果您能使用这种方法,我认为它更加美观。
UIButton
在某些UIControl
上的showsMenuAsPrimaryAction = true
行为。谢谢你! - undefined