You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Swift中如何为xib创建的CustomKeyboard使用自定义代理实现事件传值

解决方案

你可以通过闭包回调的方式实现自定义按钮点击事件传递到ViewController,修改代码如下:

1. 修改CustomKeyboard类

新增回调闭包属性,按钮点击时触发回调将按钮标题传出:

import Foundation
import UIKit
class CustomKeyboard:UIView {
    // 按钮点击回调,参数为按钮当前标题
    var onButtonTap: ((String?) -> Void)?
    
    @IBAction func rowButtonAction(_ sender: UIButton) {
        onButtonTap?(sender.currentTitle)
    }
}

2. 修改ViewController类

加载xib时转换为CustomKeyboard类型,实现回调逻辑将输入内容插入到textField2:

import UIKit
class ViewController: UIViewController {
    @IBOutlet weak var textField1: UITextField!
    @IBOutlet weak var textField2: UITextField!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // 加载自定义键盘视图并转换为CustomKeyboard类型
        guard let customKeyboard = UINib(nibName: "CustomKeyboard", bundle: nil).instantiate(withOwner: nil, options: nil).first as? CustomKeyboard else { return }
        textField1.inputAccessoryView = customKeyboard
        textField1.autocorrectionType = .no
        textField2.autocorrectionType = .no
        
        // 处理按钮点击回调
        customKeyboard.onButtonTap = { [weak self] title in
            guard let self = self, let input = title else { return }
            // 将输入内容插入到textField2的当前光标位置,适配中间插入文本的场景
            self.textField2.insertText(input)
            
            // 如果需要点击按钮直接替换textField2的全部内容,替换为下面的代码即可
            // self.textField2.text = input
        }
    }
}

说明

  • 闭包回调不需要额外定义协议,代码逻辑更集中,适合这种简单的跨组件传值场景
  • 闭包中使用[weak self]避免循环引用导致的内存泄漏
  • 所有自定义按钮只要绑定同一个rowButtonAction方法,即可自动传递对应按钮的标题,不需要额外修改代码

内容的提问来源于stack exchange,提问作者user10469417

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.17 14:36:01