以下是二进制文件:
FieldStyle1.swift :
import UIKit
protocol FieldStyle1Delegate {
func textChange(text: String, tag: NSInteger)
}
class FieldStyle1: UITableViewCell, UITextFieldDelegate {
var delegate: FieldStyle1Delegate?
@IBOutlet var fullnameField: UITextField!
@IBOutlet var usernameField: UITextField!
@IBOutlet var emailField: UITextField!
@IBOutlet var passwordField: UITextField!
@IBOutlet var confirmPasswordField: UITextField!
override func awakeFromNib() {
fullnameField.delegate = self
usernameField.delegate = self
emailField.delegate = self
passwordField.delegate = self
confirmPasswordField.delegate = self
fullnameField.tag = 0
usernameField.tag = 1
emailField.tag = 2
passwordField.tag = 3
confirmPasswordField.tag = 4
}
func textFieldDidEndEditing(_ textField: UITextField) {
delegate?.textChange(text: textField.text!, tag: textField.tag)
}
}
我需要将@IBOutlet var passwordField: UITextField!
和@IBOutlet var fullnameField: UITextField!
从FieldStyle1.swift
拉到ViewController.swift
创建用户功能,其中
user.username = usernameField.text
,但我得到“使用未解析的标识符”usernameField“错误。
我尝试过在stackoverflow上找到多个方法,但都没有成功。请帮忙!
答案 0 :(得分:0)
1)配置单元格时,必须指定符合FieldStyle1Delegate
委托的对象。如果要在视图控制器中配置单元格,则可以指定self
:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = ...
cell.delegate = self
return cell
}
2)你必须遵守该代表:
class ViewController: FieldStyle1Delegate, UITableViewDataSource {
func textChange(text: String, tag: NSInteger) {
// now you have those values
}
}
完整示例:
class ViewController: FieldStyle1Delegate, UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return ...
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = ...
cell.delegate = self
return cell
}
func textChange(text: String, tag: NSInteger) {
// now you have those values
}
}
答案 1 :(得分:0)
您无法直接从表格单元格中访问textFields所以您需要在实施时实施协议:
首先,您需要像这样从控制器向表格单元格提供FieldStyle1Delegate:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(withIdentifier:"identifier") as? FieldStyle1 else {
fatalError("Nil")
}
cell.delegate = self
return cell
}
然后你需要在视图控制器中处理它并从表格单元格中获取数据:
class ViewController: UIViewController, FieldStyle1Delegate {
func textChange(text: String, tag: NSInteger) {
if tag == 0 {
user.fullname = text
} else if tag == 1 {
user.username = text
} else if tag == 2 {
user.email = text
} else if tag == 3 {
user.password = text
}
}
}
答案 2 :(得分:0)
在viewController.swift中保持FieldStyle1类的引用
Class ViewController: UIViewController {
var xibView: FieldStyle1?
func loadNib() {
self.xibView = //..load nib
}
func accessOutlets() {
User.name = xibView?.textField.text
}
}