选择文本并更改属性会出错吗?

时间:2019-05-07 06:22:56

标签: ios swift uitextview nsattributedstring

我在进行简单的文本选择和更改属性时遇到麻烦。我似乎无法使程序超出第一步。它说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视图中调用bold()时,它将显示nil!我如何加载AccessoryView。

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

1 个答案:

答案 0 :(得分:1)

请确保在viewDidLoad()上添加textView.delegate = self。 同样在您的班级中,继承自UITextViewDelegate

然后在selectText()中呼叫您的textViewDidChangeSelection(_:)

func textViewDidChangeSelection(_ textView: UITextView) {
    selectText()
}

它将正常工作。

编辑 通常,即使您在按钮操作中调用selectText()时,它也应该起作用。但是由于它不起作用,我们来解决问题: 在课堂上声明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
}