【问题标题】:How to use custom delegate for xib in swift?如何在 swift 中为 xib 使用自定义委托?
【发布时间】:2021-08-27 03:27:15
【问题描述】:

我想使用 inputAccessoryView 在键盘上方添加自定义数字按钮。我已经添加了视图。我已将类 CustomKeyboard 分配给 xib 文件。在 CustomKeyboard 类文件中,我连接了按钮的 IBAction。我的 ViewController textField1 和 textFiled2 中有两个 textField 并且我已将 inputAccessoryView 与 textField1 相关联。当我点击 textField1 时,我的自定义按钮会显示在键盘上方。我的目标是当我点击自定义按钮时,它应该在 textFild2 中输入值。但我真的不知道我将如何实现这一目标。有人有什么想法请帮帮我。

import Foundation
import UIKit
class CustomKeyboard:UIView {
    @IBAction func rowButtonAction(_ sender: UIButton) {
        print(sender.currentTitle)
    }
    
}

import UIKit
class ViewController: UIViewController {
    @IBOutlet weak var textField1: UITextField!
    @IBOutlet weak var textField2: UITextField!
    override func viewDidLoad() {
        super.viewDidLoad()
        let view = UINib(nibName: "CustomKeyboard", bundle: nil).instantiate(withOwner: nil, options: nil)[0] as! UIView
        textField1.inputAccessoryView = view//customView
        textField1.autocorrectionType = .no
        textField2.autocorrectionType = .no
    }
}

【问题讨论】:

  • 这不够清晰。不能直接分配textField2.inputAccessoryView = view吗?
  • 不,我不想点击 textField2,因为它将由 textField1 处理

标签: ios swift xcode xib custom-keyboard


【解决方案1】:

您可以使用委托或闭包从 CustomKeyboard 回调到 ViewController。下面的示例使用委托方法,当用户点击视图时将调用函数 rowTapped。

import Foundation
import UIKit

protocol CustomKeyBoardProtocol:AnyObject{
        fun rowTapped(title:String)
}
class CustomKeyboard:UIView {

weak var delegate:CustomKeyBoardProtocol?
    @IBAction func rowButtonAction(_ sender: UIButton) {
        print(sender.currentTitle)
        delegate.rowTapped(title: sender.currentTitle)
    }

}

import UIKit
class ViewController: UIViewController,  CustomKeyBoardProtocol{
    @IBOutlet weak var textField1: UITextField!
    @IBOutlet weak var textField2: UITextField!
    override func viewDidLoad() {
        super.viewDidLoad()
        let customView = UINib(nibName: "CustomKeyboard", bundle: nil).instantiate(withOwner: nil, options: nil)[0] as! CustomKeyboard
        customView.delegate = self// he
        textField1.inputAccessoryView = customView//customView
        textField1.autocorrectionType = .no
        textField2.autocorrectionType = .no
    }


    func rowTapped(title:String){//it will be called on tap
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-02-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-13
    • 1970-01-01
    • 2017-04-15
    • 2015-11-27
    相关资源
    最近更新 更多