如何将UITableView选中单元格价格传递到目标VC的UITextField
实现方案
核心逻辑为通过单元格回调拿到当前行的价格文本,跳转前赋值给支付页的接收属性,支付页加载时自动填充到输入框即可,分三步实现:
- 第一步:给自定义单元格添加点击回调
打开你自定义的invoicesModel单元格类,添加闭包属性用于向外传递点击事件和当前价格,同时给单元格上的支付跳转按钮绑定点击事件:import UIKit class invoicesModel: UITableViewCell { @IBOutlet weak var mainPriceLabelInvoices: UILabel! @IBOutlet weak var payButton: UIButton! // 点击回调,参数为当前单元格显示的价格文本 var payButtonTapAction: ((String) -> Void)? override func awakeFromNib() { super.awakeFromNib() // 给支付按钮绑定点击事件 payButton.addTarget(self, action: #selector(payButtonClicked), for: .touchUpInside) } @objc private func payButtonClicked() { // 触发回调,传出当前价格 payButtonTapAction?(mainPriceLabelInvoices.text ?? "") } } - 第二步:在列表代理方法中处理跳转传值
回到InvoicesViewController的tableView(_:cellForRowAt:)方法,在返回cell之前设置回调逻辑,拿到价格后初始化PayViewController并传值:func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { guard let cell = tableView.dequeueReusableCell(withIdentifier: "invoicesCell", for: indexPath) as? invoicesModel else { return UITableViewCell() } // 替换原有强制解包逻辑为安全写法,避免接口异常时崩溃 guard let invoices = notifications.Result?[changeCustomerKey.DefaultsKeys.keyTwo].properties?[0].invoices else { return cell } let currentInvoices = invoices[indexPath.row] cell.mainPriceLabelInvoices.text = "€\(currentInvoices.priceWithVAT ?? 0.00)" // 处理按钮点击跳转逻辑 cell.payButtonTapAction = { [weak self] price in guard let self = self else { return } let payVC = PayViewController() // 提前在PayViewController中声明该接收属性 payVC.targetPrice = price // 保留你原有的popover弹出配置即可 payVC.modalPresentationStyle = .popover payVC.popoverPresentationController?.sourceView = cell.payButton self.present(payVC, animated: true) } return cell } - 第三步:在支付页填充输入框
打开PayViewController,先声明接收价格的属性,再在页面加载时给输入框赋值:import UIKit class PayViewController: UIViewController { @IBOutlet weak var priceTextField: UITextField! // 接收传入价格的属性 var targetPrice: String? override func viewDidLoad() { super.viewDidLoad() // 自动填充价格到输入框 priceTextField.text = targetPrice } }
注意:你原有代码中多处使用
!强制解包可选值,当接口返回空数据、异常结构时会直接触发应用崩溃,建议全部替换为可选绑定、空合运算符这类安全的可选值处理方式。
内容的提问来源于stack exchange,提问作者Lis1
相关产品推荐
相关产品推荐

