Reputation: 111
I want to enable the button in the viewcontroller when I fill in the textfield in the tableviewcell.
I don't know how to solve the problem.
Sorry. I am immature in English.
1. ViewController
import UIKit
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, UITextFieldDelegate {
@IBOutlet var tableView: UITableView!
@IBOutlet var viewLabel: UILabel!
@IBOutlet var clickBtn: UIButton!
var cell: CustomTableViewCell!
override func viewDidLoad() {
super.viewDidLoad()
self.clickBtn.isEnabled = false
cell.textFieldCell.addTarget(self, action: #selector(editingChanged), for: .editingChanged)
cell.textFieldCell2.addTarget(self, action: #selector(editingChanged), for: .editingChanged)
}
@objc func editingChanged(sender: UITextField) {
sender.text = sender.text?.trimmingCharacters(in: .whitespaces)
guard
let text1 = cell.textFieldCell.text, !text1.isEmpty,
let text2 = cell.textFieldCell2.text, !text2.isEmpty
else
{
self.clickBtn.isEnabled = false
return
}
clickBtn.isEnabled = true
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 1
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
cell = tableView.dequeueReusableCell(withIdentifier: "myCell", for: indexPath) as! CustomTableViewCell
return cell
}
}
2. CustomTableView
import UIKit
class CustomTableViewCell: UITableViewCell, UITextFieldDelegate {
@IBOutlet var myLabel: UILabel!
@IBOutlet var textFieldCell: UITextField!
@IBOutlet var textFieldCell2: UITextField!
}
Upvotes: 0
Views: 211
Reputation: 124
One option is to use delegate.
protocol CustomTableViewCellDelegate {
func editingChanged(_ String: yourString)
}
In table view cell
class TableViewCell: UITaleViewCell {
// declare the delegate
var delegate: CustomTableViewCellDelegate?
// and pass it like this from where you want to pass
delegate?.editingChanged(cookie)
}
For using in tableViewController. first assign the delegate to self in cell for row at indexpath method. Then implement the delegate in it.
extension CustomTableViewController: CustomTableViewCellDelegate {
func editingChanged(String: yourString) {
// use it accordingly
}
}
Upvotes: 0
Reputation: 285082
As the table view contains only one cell why do you use a table view at all?
And if you really need to use a table view why don't you use a static cell?
A simple solution is to move the target/action code from viewDidLoad
into the didSet
property observer of the cell
var cell: CustomTableViewCell! {
didSet {
cell.textFieldCell.addTarget(self, action: #selector(editingChanged), for: .editingChanged)
cell.textFieldCell2.addTarget(self, action: #selector(editingChanged), for: .editingChanged)
}
}
override func viewDidLoad() {
super.viewDidLoad()
self.clickBtn.isEnabled = false
}
Upvotes: 2