是否有可能推翻UITextView
对cmd + z
和cmd + shift + z
的处理?
我试过
keyCommand
属性,但选择器从未被调用..。undoManager
,这也没有帮助class CustomTextView: UITextView {
override var keyCommands: [UIKeyCommand]? {
[
// cmd + z (doesn't work)
UIKeyCommand(input: "z", modifierFlags: [.command], action: #selector(undo)),
// cmd + shift + z (doesn't work)
UIKeyCommand(input: "z", modifierFlags: [.command, .shift], action: #selector(redo)),
// z (works)
UIKeyCommand(input: "z", modifierFlags: [], action: #selector(z)),
]
}
// this doesn't help
override var undoManager: UndoManager? { return nil }
// undo
@objc private func undo() {
print("undo")
}
// redo
@objc private func redo() {
print("redo")
}
// z
@objc private func z() {
print("z")
}
}
发布于 2021-12-16 18:10:49
您可以使用UITextView+UIResponder.swift扩展来完成这一任务:
import UIKit
extension UITextView {
static var myUndoManager = UndoManager()
fileprivate func handleUndo () { ... }
fileprivate func handleRedo () { ... }
override var undoManager : UndoManager? {
return Self.myUndoManager
}
override func pressesBegan (
_ presses: Set<UIPress>
, with event: UIPressesEvent?
)
{
for press in presses {
guard
let key = press.key
, key.charactersIgnoringModifiers == "z"
else { continue }
switch key.modifierFlags {
case .command:
handleUndo()
case [ .command, .shift]:
handleRedo()
default:
break
}
}
super.pressesBegan (
presses
, with: event
)
}
}
相关苹果参考资料:
func pressesBegan(_:)
https://developer.apple.com/documentation/uikit/uiresponder
class UIKey
https://developer.apple.com/documentation/uikit/uikey
另见:应答器 https://stackoverflow.com/questions/tagged/uiresponder
为什么覆盖keyCommands
不起作用?
UITextView是不透明的,所以我无法亲眼看到,但我认为它会覆盖pressesBegan(_:with:)
,并且不会调用super
来处理任何按键。如果没有对super
的调用,UIPressesEvent
事件就不会在响应链上传播;keyCommands
永远不会看到它们。
https://stackoverflow.com/questions/67597936
复制相似问题