gpt4 book ai didi

swift - 使用 attributedText 在 UITextView 中实现撤消和重做

转载 作者:搜寻专家 更新时间:2023-11-01 07:02:10 26 4
gpt4 key购买 nike

我正在尝试将撤消重做 功能添加到我的UITextView 实现中。我使用的是 attributedText 而不仅仅是 UITextViewtext 属性。我尝试使用 undoManager 中的函数调用,如 Apple documentation 中引用的那样,但是似乎什么也没有发生。令我惊讶的是,我无法通过谷歌搜索找到有关该主题的任何内容。在使用 attributedTextUITextView 实现撤消和重做之前,有没有人遇到过这个问题/知道如何解决这个问题?

示例代码

textView.attributedText = NSMutableAttributedString(string: "SOME TEXT")

@objc func undo(_ sender: UIButton) {
textView.undoManager?.undo()
}

@objc func redo(_ sender: UIButton) {
textView.undoManager?.redo()
}

最佳答案

下面是一些示例代码,用于处理 UITextView 的撤消/重做。不要忘记在每次更改文本后更新撤消/重做按钮的状态。

class ViewController: UIViewController {

@IBOutlet weak var textView: UITextView!
@IBOutlet weak var undoButton: UIButton!
@IBOutlet weak var redoButton: UIButton!

override func viewDidLoad() {
super.viewDidLoad()

updateUndoButtons()
}

@IBAction func undo(_ sender: Any) {
textView.undoManager?.undo()
updateUndoButtons()
}

@IBAction func redo(_ sender: Any) {
textView.undoManager?.redo()
updateUndoButtons()
}

func updateUndoButtons() {
undoButton.isEnabled = textView.undoManager?.canUndo ?? false
redoButton.isEnabled = textView.undoManager?.canRedo ?? false
}
}

extension ViewController: UITextViewDelegate {

func textViewDidChange(_ textView: UITextView) {
updateUndoButtons()
}
}

显然,您需要在 Storyboard中连接 Action /导出和 TextView 的委托(delegate)导出

关于swift - 使用 attributedText 在 UITextView 中实现撤消和重做,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50528946/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com