【发布时间】:2019-05-07 06:22:55
【问题描述】:
我在进行简单的文本选择和属性更改时遇到问题。我似乎无法让程序通过第一步。它说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?
}
【问题讨论】:
-
您如何访问
KeyboardAccessory以及此let VC = ViewController()创建此ViewController的新实例,该实例与您正在访问的当前实例不同。 -
好的。如果我在页面上创建一个新按钮,它就会起作用,所以这与之间的通信有关。我已经使用加载 AccessoryView 的代码对其进行了更新。非常感谢你的帮助! :)
标签: ios swift uitextview nsattributedstring