我正在尝试在我的应用程序中创建一个可重用的 UI 组件,该特定组件包含一个 UITextFeild。我已成功在 View 中设置文本字段并且它显示完美,但是...文本字段委托(delegate)设置不起作用。
我尝试像这样从创建的对象引用文本字段
let sessionNameCell = ReusableComponents().createTextFieldCell()
sessionNameCell.textField.delegate = self
但无法从 Controller 引用文本字段。
我还尝试在创建 View 的函数内部以多种方式设置委托(delegate):
textField.delegate = self
和
textField.delegate = ViewController()
最后一个使应用程序崩溃,据我所知,创建对象的实例不是合适的解决方案
完整代码是...
View Controller
class HostSessionSetupController : UITableViewController, UITextFieldDelegate {
private var sessionNameCell: UITableViewCell = ReusableComponents().createEditableTableRow(title: "Session Name", placeholder: "e.g. Marks birthday")
override func viewDidLoad() {
super.viewDidLoad()
sessionNameCell.textField.delegate = self
}
// The delegate method i need to run
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
if let input = textField.text {
if input != ""{
self.title = "Setup " + input
} else {
self.title = "Setup Session"
}
}
}
查看功能
func createTableRow(title: String, accessoryType: UITableViewCell.AccessoryType = .none) -> UITableViewCell {
let cell = UITableViewCell()
cell.backgroundColor = .backgroundDarkBlack
cell.textLabel?.textColor = .white
cell.textLabel?.text = title
cell.selectionStyle = .none
cell.accessoryType = accessoryType
return cell
}
func createEditableTableRow(title: String, placeholder: String) -> UITableViewCell{
let cell = createTableRow(title: title)
let textField = UITextField(frame: CGRect(x: 40, y: 0, width: cell.frame.width, height: cell.frame.height))
textField.textColor = .white
textField.attributedPlaceholder = NSAttributedString(string: placeholder, attributes: [NSAttributedString.Key.foregroundColor: UIColor.init(white: 1, alpha: 0.5)])
textField.keyboardAppearance = .dark
textField.returnKeyType = .default
textField.textAlignment = .right
cell.addSubview(textField)
return cell
}
我试图从这一切中获得的唯一功能是在键盘返回时隐藏键盘! D:
感谢您的帮助!
最佳答案
创建单元格时需要设置TextField的委托(delegate)
关于swift - 创建可重用 View 时如何分配 TextField 委托(delegate)和方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54468827/