问题描述
我想将 modalViewController 的表格单元格数据传递给主视图。
使用协议委托。但是
Fatal error: Unexpectedly found nil while implicitly unwrapping an Optional value
这个错误发生在我在 ModalViewController 上评论的地方。
使用Protocol方法有错吗?。 我使用此协议代码来回传递另一个迷你项目 textField 的文本数据。在那里它运作良好。 所以我在单元格数据传递中使用它
我想念什么?请帮忙。
ModalTableViewDataPass **主视图控制器**import UIKit
class ViewController: UIViewController,UITextFieldDelegate {
@IBOutlet weak var show: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
show.placeholder = "HAHA"
show.delegate = self
show.inputView = UIView()
show.addTarget(self,action: #selector(textFieldDidBeginEditing(_:)),for: .touchUpInside)
// Do any additional setup after loading the view.
}
@objc func textFieldDidBeginEditing(_ textField: UITextField) {
if textField == show {
movetoFindAdrVC()
print("주소 검색해라잉")
}
}
func movetoFindAdrVC() {
let modalVC = storyboard?.instantiateViewController(identifier: "ModalViewController") as? ModalViewController
self.present(modalVC!,animated: true,completion: nil)
}
}
extension ViewController: PassDataToVc {
func passData(str: String){
show.text = str
}
}
ModalTableView
import UIKit
class ModalViewController: UIViewController,UITableViewDelegate,UITableViewDataSource {
var data = ["as","df","qw","er"]
var delegate: PassDataToVc!
@IBOutlet weak var table: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
table.delegate = self
table.dataSource = self
// Do any additional setup after loading the view.
}
func tableView(_ tableView: UITableView,numberOfRowsInSection section: Int) -> Int {
return data.count
}
func tableView(_ tableView: UITableView,cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell",for: indexPath)
cell.textLabel?.text = data[indexPath.row]
return cell
}
func tableView(_ tableView: UITableView,didSelectRowAt indexPath: IndexPath) {
let passData = data[indexPath.row]
let sb = storyboard?.instantiateViewController(identifier: "ViewController") as? ViewController
//sb?.show.text = passData
delegate.passData(str: passData)//Fatal error: Unexpectedly found nil while implicitly unwrapping an Optional value
self.dismiss(animated: true,completion: nil)
}
}
protocol PassDataToVc {
func passData(str: String)
}
解决方法
delegate
中的 ModalViewController
从未设置,因此它是 nil
。
但是有一个更方便的解决方案,完全不需要协议/委托。
删除protocol/delegate相关的代码
extension ViewController: PassDataToVc {
func passData(str: String){
show.text = str
}
}
var delegate: PassDataToVc!
罢工>
并替换
delegate.passData(str: passData)
与
(presentingViewController as? ViewController)?.show.text = passData