首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >重写UITextView的CMD +Z key命令

重写UITextView的CMD +Z key命令
EN

Stack Overflow用户
提问于 2021-05-19 06:22:39
回答 1查看 184关注 0票数 2

是否有可能推翻UITextViewcmd + zcmd + shift + z的处理?

我试过

  • 重写keyCommand属性,但选择器从未被调用..。
  • 覆盖undoManager,这也没有帮助
代码语言:javascript
运行
复制
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")
    }   
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-12-16 18:10:49

您可以使用UITextView+UIResponder.swift扩展来完成这一任务:

代码语言:javascript
运行
复制
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永远不会看到它们。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/67597936

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档