【问题标题】:Using a Button to add text to a text field value that is contained within a UITableViewcell使用 Button 将文本添加到 UITableViewcell 中包含的文本字段值
【发布时间】:2019-07-12 06:43:36
【问题描述】:

我正在寻找一个 UIButton 以将其标题值添加到当前选定的 UITextField 中,该 UITextField 包含在 UITableViewCell 中。

我有一排按钮,其中包含用户可能使用的常用短语,例如“#CompanyName”。我已将常用短语设置为按钮的标题。就在按钮行下方,我有一个UITableView,每个单元格都包含几个静态标签和一个文本字段。我想让用户按下表格视图上方的按钮之一,将按钮的标题值添加到当前正在编辑的文本字段中。

我已经设法使用文本字段和按钮进行测试,这两个按钮都在表格视图之外,使用:

    @IBAction func buttonAction(_ sender: AnyObject) {
        buttonTitle = sender.titleLabel!.text!
        testOutlet.text = "\(testOutlet.text!) \(buttonTitle)"

现在我的问题是如何使这个“testOutlet.text”动态化,以便它只知道正在编辑的文本字段。我已经查看了textFieldDidBeginEditing,但无法弄清楚。我也尝试过定义 indexPath。

【问题讨论】:

    标签: ios swift uitableview cocoa-touch uitextfield


    【解决方案1】:

    您需要知道当前正在编辑哪个UITextField。为此,您可以使用以下代码:

    class ViewController: UIViewController {
        // code ...
    
        @IBAction func buttonAction(_ sender: AnyObject) {
            buttonTitle = sender.titleLabel!.text!
            oActiveTextField?.text = "\(oActiveTextField?.text ?? "") \(buttonTitle)"
        }
    
        fileprivate var oActiveTextField: UITextField?
    }
    
    extension ViewController: UITableViewDataSource {
        // code ...
    
        func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
            let cell = tableView.dequeueReusableCell(withIdentifier: yourIdentifier, for: indexPath) as! YourTableViewCell
            cell.textField.delegate = self
            // TODO: configure cell
            return cell
        }
    }
    
    extension ViewController: UITextFieldDelegate {
    
        func textFieldDidBeginEditing(_ textField: UITextField) {
            oActiveTextField = textField
        }
    
        func textFieldDidEndEditing(_ textField: UITextField) {
            oActiveTextField = nil
        }
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-03-25
      • 1970-01-01
      • 2012-02-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多