首页 > 解决方案 > 使用 IQKeyBoardManager 时键盘 titleBarButton 的属性文本问题

问题描述

我正在将 IQKeyboardManager 与 Swift 一起使用。我在日期选择器上添加了一个取消按钮。一切正常,但我遇到了取消按钮的属性文本没有生效的问题。我究竟做错了什么?这是一个代码片段

cell.field.attributedPlaceholder = NSAttributedString(string: "Cancel",
            attributes: [.foregroundColor: UIColor.black,
               .font: UIFont.boldSystemFont(ofSize: 12)])

cell.field.keyboardToolbar.titleBarButton.setTarget(self,
        action:#selector(datePickerWasCanceled(sender:)))

这是当前结果的示例屏幕截图——我原以为取消应该是黑色和粗体。

键盘取消按钮没有指定属性

标签: iosswiftiqkeyboardmanager

解决方案


使用 UIBarButtonItem 而不是 attributesPlaceholder,两边都有一个灵活的空间,这样您就可以将它放置在工具栏的中间。

var items: [UIBarButtonItem] = []

let flexSpace = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
let cancel: UIBarButtonItem = UIBarButtonItem(title: "Cancel", style: .done, target: self, action: #selector(self.datePickerWasCanceled))
cancel.setTitleTextAttributes([
  NSAttributedStringKey.font: UIFont.boldSystemFont(ofSize: 17.0),
  NSAttributedStringKey.foregroundColor: UIColor.blue], for: .normal)

items.append(flexSpace)
items.append(cancel)
items.append(flexSpace)

cell.field.keyboardToolbar.items = items
cell.field.keyboardToolbar.sizeToFit()


@objc func datePickerWasCanceled() {
  cell.field.resignFirstResponder()
}

推荐阅读