我想将ViewControllerC
中文本字段中的文本发送到ViewControllerA
使用委托我尝试将文字从ViewControllerC
传递到ViewControllerA
。
我无法在delegate?.userDidEnterInformation()
ViewControllerC
任何人都可以帮我解决这个问题
ViewControllerC
protocol DataEnteredInDestinationDelegate: class {
func userDidEnterInformation(info: String)
}
class DestinationSearchViewController: MirroringViewController {
var delegate: DataEnteredInDestinationDelegate?
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let cell: UITableViewCell? = tableView.cellForRow(at: indexPath)
componetsTextField.text = cell?.textLabel?.text
delegate?.userDidEnterInformation()
self.navigationController?.popToRootViewController(animated: true)
}
}
ViewControllerA
class HomeViewController: MirroringViewController, DataEnteredInDestinationDelegate
{
func userDidEnterInformation(info: String){
locationView.destination.text = info
}
}
答案 0 :(得分:0)
delegate?.userDidEnterInformation(cell!.textLabel!.text)
此外,您应该设置ViewControllerC
的代表。
viewControllerC.delegate = viewControllerA
答案 1 :(得分:0)
首先,您必须始终将委托标记为weak
,例如:
weak var delegate: DataEnteredInDestinationDelegate?
然后你需要像这样连接委托:
let vcA = ViewControllerA()
let vcC = ViewControllerC()
vcC.delegate = vcA // Connect delegate
然后在调用此代码后,ViewControllerC中的委托方法将起作用:
delegate?.userDidEnterInformation(textString)
答案 2 :(得分:0)
这里NotificationCentre可以是一个很好的方法,而不是代表。使Viewcontroller成为一个观察者,接收如下文本信息。
在viewDidLoad()
中编写此代码NotificationCenter.default.addObserver(self, selector: #selector(userDidEnterInformation(notification:)), name: NSNotification.Name.init(rawValue: "UserDidEnterInformation"), object: nil)
并在Viewcontroller A类中的任何地方写这个
func userDidEnterInformation(notification: Notification) {
if let textInfo = notification.userInfo?["textInfo"] {
textField.text = textInfo
}
}
在Viewcontroller C中,通过编写下面的代码
发布带有textInfo的通知NotificationCenter.default.post(name: NSNotification.Name.init(rawValue: "UserDidEnterInformation"), object: nil, userInfo: ["textInfo": textField.text])
答案 3 :(得分:0)
考虑以下示例: -
let aVCobjA = UIViewController()
let aVCobjB = UIViewController()
let aVCobjC = UIViewController()
var aNavigation = UINavigationController()
func pushVC() {
aNavigation.pushViewController(aVCobjA, animated: true)
aNavigation.pushViewController(aVCobjB, animated: true)
aNavigation.pushViewController(aVCobjC, animated: true)
//Here you will get array of ViewControllers in stack of Navigationcontroller
print(aNavigation.viewControllers)
//To pass data from Viewcontroller C to ViewController A
self.passData()
}
// To pass data access stack of Navigation Controller as navigation controller provides a property viewControllers which gives you access of all view controllers that are pushed.
func passData() {
let aVCObj3 = aNavigation.viewControllers.last
let aVCObj1 = aNavigation.viewControllers[0]
//Now you have access to both view controller pass whatever data you want to pass
}