我目前正在开发一个项目,该项目有一个创建帐户页面,该页面由一个名为 CreateNewAccount 的 View Controller 和一个伴随它的同名类表示。有四个值被输入到这个 View Controller 中:1) firstName,2) lastName,3) username,和 4) password。这个 View Controller 还有一个“创建帐户”按钮,当按下该按钮时,应该将在 4 个输入中输入的字符串值传输到一个名为 UInfoRetrieveModel 的新类,该类在 MVC 配置下将被归类为模型。不幸的是,这个值(value)转移部分不起作用。
然后我让 UInfoRetrieveModel 将这 4 个值直接传递给另一个名为 UserInfo 的模型,然后将这些值中的任何一个委托(delegate)给 UI 端可能需要显示它们的其他 View Controller 。我已经弄清楚如何将值从 UInfoRetrieveModel 传递到 UserInfo 以及从 UserInfo(这是一个模型)传递到所述 View Controller ,但我还没有弄清楚如何从 View Controller 传递值,特别是 CreateNewAccount,到模型,在这种情况下是 UInfoRetrieveModel。
基本上我的想法是有两个模型类:一个模型接收 (UInfoRetrieveModel) 和一个委托(delegate)出 (UserInfo) 在 CreateNewAccount 中设置的数据值,以便更有效地跨 UI 传输数据。
下面是我的 CreateNewAccount 和 UInfoRetrieveModel 代码,其中传输似乎不起作用:
UInfoRetrieveModel->
import Foundation
protocol UInfoRetrieveModelDelegate: class {
func credentialTransfer(data:String)
}
class UInfoRetrieveModel: NSObject {
weak var delegate: UInfoRetrieveModelDelegate?
var firstName: String = ""
var lastName: String = ""
var userName: String = ""
var password: String = ""
func retrieving(){
delegate?.credentialTransfer(data: firstName)
delegate?.credentialTransfer(data: lastName)
delegate?.credentialTransfer(data: userName)
delegate?.credentialTransfer(data: password)
}
}
创建新账户->
import UIKit
class CreateNewAccount: UIViewController{
@IBOutlet weak var FNInput: UITextField!
@IBOutlet weak var LNInput: UITextField!
@IBOutlet weak var usernameInput: UITextField!
@IBOutlet weak var passwordInput: UITextField!
var uInfoRetrieve = UInfoRetrieveModel()
@IBAction func thanksForJoining(_ sender: Any) {
uInfoRetrieve.firstName = FNInput.text!
uInfoRetrieve.lastName = LNInput.text!
uInfoRetrieve.userName = usernameInput.text!
uInfoRetrieve.password = passwordInput.text!
uInfoRetrieve.retrieving()
uInfoRetrieve.delegate = self
}
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
extension CreateNewAccount: UInfoRetrieveModelDelegate{
func credentialTransfer(data: String) {
print(data)
}
}
最佳答案
您以错误的顺序调用了 retrieving()
。请改用此顺序:
@IBAction func thanksForJoining(_ sender: Any) {
uInfoRetrieve.firstName = FNInput.text!
uInfoRetrieve.lastName = LNInput.text!
uInfoRetrieve.userName = usernameInput.text!
uInfoRetrieve.password = passwordInput.text!
uInfoRetrieve.delegate = self
uInfoRetrieve.retrieving()
}
原因:如果在设置委托(delegate)之前调用retreiving()
,委托(delegate)将为nil
,您将得不到回调。
关于swift - 如何将数据从 View Controller 传递到模型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51936643/