在表单表视图的自定义单元格中检索uitextfield文本



这里是我的问题,我需要在extfields中填充自定义单元格,但我无法区分不同的单元格。有一次,我为每个单元格找到了一种使用某种"模式"的解决方案,但再也找不到了。

我的自定义单元格

class RegisterFormCell: UITableViewCell {
@IBOutlet weak var myInputField: UITextField!
@IBOutlet weak var myButton: UIButton!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}

}

我的主控制器

import UIKit
class ViewController: UIViewController {
@IBOutlet weak var myTable: UITableView!
@IBOutlet weak var confimButtonOut: UIButton!
let fields = ["Name", "Email"]
let name = ""
let email = ""
override func viewDidLoad() {
super.viewDidLoad()
myTable.delegate = self
myTable.dataSource = self
}

@objc func actionForButtonInsideCell() {
print("tapped")
}
@IBAction func confirmButtonTapped(_ sender: Any) {
//verify validation for data
if name != "" && email.isValidEmail() {
print("all is ok, perform segue")
} else {
print("some error")
}

}
}

extension ViewController: UITableViewDelegate, UITableViewDataSource {

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return fields.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = myTable.dequeueReusableCell(withIdentifier: "RegisterFormCell-id", for: indexPath) as! RegisterFormCell
cell.myInputField.placeholder = fields[indexPath.row]
cell.myInputField.delegate = self
cell.myButton.addTarget(self, action: #selector(actionForButtonInsideCell), for: .touchUpInside)
//        switch indexPath.row {
//        case 0:
//            break
//        default:
//            cell.myButton.isHidden = true
//        }
return cell
}

func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return "test title"
}
}

extension ViewController: UITextFieldDelegate {
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
print("final is: (textField.text ?? "error")")
return true
}
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
guard textField.text != "", textField.text != nil else { return true}
//here should be assigned the value to the variables
print(textField.text!)
return true
}
}

extension String {
func isValidEmail() -> Bool {
// here, `try!` will always succeed because the pattern is valid
let regex = try! NSRegularExpression(pattern: "^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$", options: .caseInsensitive)
return regex.firstMatch(in: self, options: [], range: NSRange(location: 0, length: count)) != nil
}
}

您应该在RegisterFormCell类中实现UITextfield委托,而不是在ViewController上实现,这样您就可以单独控制每个单元格对应的文本字段。

最新更新