【问题标题】:Single extension for TextView and TextField to add a toolBarTextView 和 TextField 的单个扩展以添加工具栏
【发布时间】:2020-08-04 18:24:28
【问题描述】:

我想创建一个扩展来在键盘上为 TextView 和 TextField 添加一个工具栏。

现在我在 TextView 和 TextField 上都这样做:

extension UITextView {
func setKeyboardToolBar(items: [UIBarButtonItem]) {
    let screenWidth = UIScreen.main.bounds.width
    let toolBar = UIToolbar(frame: CGRect(x: 0.0, y: 0.0, width: screenWidth, height: 44.0))
    toolBar.setItems(items, animated: false)
    self.inputAccessoryView = toolBar
}

}

但是在 2 个不同的扩展中拥有完全相同的功能是很烦人的。

我尝试像在这个问题 Single extension for UITextView and UITextField in Swift 中那样扩展 UIView,但 inputAccessoryView 出现错误,因为它是一个只能获取的属性。

如何分解这两个相同的函数?

【问题讨论】:

    标签: ios swift uitextfield uitextview


    【解决方案1】:

    也许这会对你有所帮助:

    extension UITextField: KeyboardToolbarCompatible {}
    extension UITextView: KeyboardToolbarCompatible {}
    
    protocol KeyboardToolbarCompatible: AnyObject {
        func setKeyboardToolBar(items: [UIBarButtonItem])
        var inputAccessoryView: UIView? { get set }
    }
    
    extension KeyboardToolbarCompatible {
        func setKeyboardToolBar(items: [UIBarButtonItem]) {
            let screenWidth = UIScreen.main.bounds.width
            let toolBar = UIToolbar(frame: CGRect(x: 0.0, y: 0.0, width: screenWidth, height: 44.0))
            toolBar.setItems(items, animated: false)
            self.inputAccessoryView = toolBar
        }
    }
    

    如果仅 TextView 和 TextField 需要,则 KeyboardToolbarCompatible 可以向 UITextInput 确认。

    protocol KeyboardToolbarCompatible: UITextInput { ... }
    

    【讨论】:

      猜你喜欢
      • 2020-11-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-06
      • 2017-05-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多