我正在实现一个 UITableViewController,它有 3 个部分,前两个部分分别包含 2 个和 1 个文本字段。我在访问文本字段中的文本输入时遇到问题。我不知道如何在 iOS swift 中解决这个问题,请帮忙。
在 TableView Controller 中
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let gender = Gender(rawValue: indexPath.row)
switch indexPath.section {
case 0:
guard let nameCell = tableView.dequeueReusableCellWithIdentifier("addNameCellID") as? ChildFormViewCell else {
return UITableViewCell()
}
nameCell.firstNameField.text = "" // just in case cells are re-used, this clears the old value
nameCell.firstNameField.tag = indexPath.row
return nameCell
case 1:
self.tableView.rowHeight = 50
guard let dateCell = tableView.dequeueReusableCellWithIdentifier("addDateCellID") as? ChildFormViewCell else {
return UITableViewCell()
}
return dateCell
case 2:
guard let genderCell = tableView.dequeueReusableCellWithIdentifier("addGenderCellID") as? ChildFormViewCell else {
return UITableViewCell()
}
genderCell.genderLabel.text = gender?.nameString()
return genderCell
default:
return UITableViewCell()
}
}
extension AddChildFormTVC: ChildFormViewCellDelegate {
func getFirstName(text: String?) {
print(text)
}
func getLastName(text: String?) {
print(text)
}
func getDateOfBirth(text: String?) {
print(text)
}
func getGender(text: String?) {
print(text)
}
}
<小时/>
class ChildFormViewCell: UITableViewCell {
@IBOutlet weak var firstNameField: UITextField!
@IBOutlet var lastNameField: UITextField!
@IBOutlet var dateField: UITextField!
@IBOutlet var genderLabel: UILabel!
var delegate: ChildFormViewCellDelegate!
}
extension ChildFormViewCell: UITextFieldDelegate {
func textFieldDidEndEditing(textField: UITextField) {
switch(textField) {
case self.firstNameField:
self.delegate.getFirstName(firstNameField.text)
case self.lastNameField:
self.delegate.getLastName(lastNameField.text)
case self.dateField:
self.delegate.getDateOfBirth(dateField.text)
case self.genderLabel:
self.delegate.getGender(genderLabel.text)
default:
return
}
}
}
protocol ChildFormViewCellDelegate {
func getFirstName(text: String?)
func getLastName(text: String?)
func getDateOfBirth(text: String?)
func getGender(text: String?)
}
最佳答案
然后尝试:
//This will call back after focus is lost from the input
self.textField.addTarget(self, action: #selector(updateFirstName), forControlEvents: .EditingDidEnd)
//This will call back with every change, i.e. each letter
self.textField.addTarget(self, action: #selector(updateFirstName), forControlEvents: .EditingChanged)
此外,在将 self
添加为目标的情况下,self
表示 UITableViewController
。据我所知,一个对象不能是它自己的委托(delegate)。如果可能的话那就毫无意义了。
关于ios - 从 UITableViewCell 中的 UITextField 访问文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36456639/