选择文本和更改属性错误?

Selecting text and changing attributes bug?

我在进行简单的文本选择和属性更改时遇到问题。我似乎无法让程序通过第一步。它说 selectedRange 为零。为什么会这样?这是什么东西的错误吗?

func selectText() {
    if let textRange = textView?.selectedRange {
        let attributes = [NSAttributedString.Key.font: UIFont(name: "Arial", size: 18.0)]
        textView.textStorage.addAttributes(attributes as [NSAttributedString.Key : Any], range: textRange)
    }
}

使用来自@DionizB 的代码进行编辑(无效)

我从另一个包含 KeyboardAccessory 视图的 Swift 文件调用它。该文件中的代码是:

class KeyboardAccessory: UIView {
let VC = ViewController()
@IBAction func boldButtonTapped(_ sender: Any) {
    print("boldButtonTapped -> Sending to bold()")
    VC.bold()
    }
}

现在主要 ViewController 中的代码是:

var selectedRange: NSRange?

func textViewDidChangeSelection(_ textView: UITextView) {
    selectedRange = textView.selectedRange
    print(selectedRange)
}

func bold() {
    print("Starting bold()")
    print(selectedRange)
    if let textRange = selectedRange {
        print(textRange)
        let attributes = [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 17, weight: UIFont.Weight.thin)]
        textView.textStorage.addAttributes(attributes as [NSAttributedString.Key : Any], range: textRange)
    }
}

textViewDidChangeSelection 正在打印 selectedRange,但是当从 KeyboardAccessory View 调用 bold() 时,它打印 nil!我如何加载 AccessoryView。

override func viewDidLoad() {
    super.viewDidLoad()
    textView.inputAccessoryView = Bundle.main.loadNibNamed("KeyboardAccessory", owner: self, options: nil)?.first as! UIView?
}

viewDidLoad() 上确保添加 textView.delegate = self。 同样在您的 class 继承自 UITextViewDelegate.

然后在textViewDidChangeSelection(_:)

打电话给你的selectText()
func textViewDidChangeSelection(_ textView: UITextView) {
    selectText()
}

它会正常工作。

编辑 通常,即使您在按钮操作中调用 selectText() ,它也应该可以工作。但由于它不起作用,让我们做一个解决方法: 在 class.

中声明 var selectedRange: NSRange?

然后在

func textViewDidChangeSelection(_ textView: UITextView) {
    selectedRange = textView.selectedRange
}

然后在您的 selectText() 中执行此操作

func selectText() {
    if let textRange = selectedRange {
        let attributes = [NSAttributedString.Key.font: UIFont(name: "Arial", size: 18.0)]
        textView.textStorage.addAttributes(attributes as [NSAttributedString.Key : Any], range: textRange)
    }
}

编辑 AccessoryView

更新您的键盘配件:

class KeyboardAccessory: UIView {
    var boldAction: (() -> Void)? // This is a closure, give it a read after making your button work
    @IBAction func boldButtonTapped(_ sender: Any) {
        print("boldButtonTapped -> Sending to bold()")
        boldAction?()
    }
}

尝试将加载的笔尖转换为 KeyboardAccessory 并像这样访问您的操作:

override func viewDidLoad() {
    super.viewDidLoad()
    var keyboardAccessory = Bundle.main.loadNibNamed("KeyboardAccessory", owner: self, options: nil)?.first as! KeyboardAccessory?
    keyboardAccessory.boldAction = { [weak self] in // to avoid retain cycles, read also about these
        self?.selectText()
    }
    textView.inputAccessoryView = keyboardAccessory
}