I'm looking to get a UIButton
to add its title value to the currently selected UITextField
that's contained within a UITableViewCell
.
I have a row of buttons with common phrases that a user might use, such as "#CompanyName". I have set the common phrases as the title of the buttons. Just below the row of buttons I have a UITableView
with cells each containing several static labels and a text field. I want to allow the user to press one of the buttons above the table view to add the button's title value to the text field that is currently being edited.
I have managed to do this as a test using a text field and buttons both being outside of the table view using:
@IBAction func buttonAction(_ sender: AnyObject) {
buttonTitle = sender.titleLabel!.text!
testOutlet.text = "\(testOutlet.text!) \(buttonTitle)"
Now my question is how would I make this "testOutlet.text" dynamic so it only knows the text field that's being edited. I've looked into textFieldDidBeginEditing
but couldn't figure it out. I have also tried defining the indexPath.
You need to know which UITextField
is currently being edited. To do this, you can use the following code:
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
}
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments