我在进行简单的文本选择和更改属性时遇到麻烦。我似乎无法使程序超出第一步。它说selectedRange为nil。为什么会这样呢?这是一个有问题的错误吗?

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视图中调用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
同样在您的类中,从UITextViewDelegate继承。

然后在selectText()中调用您的textViewDidChangeSelection(_:)

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的

更新您的KeyboardAccessory:
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
}

07-24 15:31