我知道那是 5 年前的事了,但它可能会帮助像我一样偶然发现你的问题的其他人。
我使用 UIToolbar 作为我的 inputAccessoryView(在我的例子中,它有一个标签、一个灵活的分隔符和一个按钮)。在 textFieldEditingChanged 事件中,我像这样重建工具栏的一部分
@IBAction func textFieldEditingChanged(_ sender: UITextField) {
//get a reference to the toolbar
let toolBar = sender.inputAccessoryView as! UIToolbar
//create a new label and set size + other properties
toolbarLabel = UILabel(frame: CGRect(x: 0, y: 0, width: 40, height: 22))
toolbarLabel.text = mySpecificCalculatedString(sender.text!)
toolbarLabel.font = defaultFont(17)
toolbarLabel.adjustsFontSizeToFitWidth = true
let width = toolbarLabel.textRect(forBounds: CGRect(x: 0, y: 0, width: maxWidthForLabel, height: 0), limitedToNumberOfLines: 1).size.width
toolbarLabel.frame = CGRect(x: 0, y: 0, width: width, height: 22)
toolbarLabel.textColor = .black
toolbarLabel.tag = 666
//rebuild the specific tolbar item
let customView = UIBarButtonItem(customView: toolbarLabel)
toolBar.items![0] = customView
}
注意:简单地更改标签的文本对我也不起作用,我不得不重新初始化它。
希望能帮助到你。