在展开del UIlabel时出现错误
@IBOutlet weak var del: UILabel!
//我的标签必须通过协议实现更改
del.text = name
//错误在这里
意外发现nil,同时隐式展开一个可选值
ViewController.swift
class ViewController: UIViewController,DataPass {
@IBOutlet weak var del: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
}
@IBAction func seconeView(_ sender: UIButton) {
let selview = storyboard?.instantiateViewController(withIdentifier: "SecondViewController")as!SecondViewController
present(selview,animated: true,completion: nil)
}
func pass(name: String) {
del.text = name // error here Unexpectedly found nil while implicitly unwrapping an Optional value
}
}
SecondViewController.swift
protocol DataPass {
func pass(name:String)
}
class SecondViewController: UIViewController {
let delegate:DataPass! = ViewController()
let label = "Delegate"
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
@IBAction func endView(_ sender: UIButton) {
if let del = delegate {
del.pass(name: label)
} else {
print("Delegate property is not set")
}
dismiss(animated: true, completion: nil)
}
}
答案 0 :(得分:0)
要使您的delegate
正常运行,您只需要做一些更改:
在第二个控制器中进行以下更改:
protocol DataPass {
func pass(name:String)
}
class SecondViewController: UIViewController {
var delegate:DataPass?
let label = "Delegate"
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
@IBAction func endView(_ sender: UIButton) {
if let del = delegate {
del.pass(name: label)
} else {
print("Delegate property is not set")
}
dismiss(animated: true, completion: nil)
}
}
并在第一个控制器中:
class ViewController: UIViewController,DataPass {
@IBOutlet weak var del: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
}
@IBAction func seconeView(_ sender: UIButton) {
let selview = storyboard?.instantiateViewController(withIdentifier: "SecondViewController")as!SecondViewController
selview.delegate = self
present(selview,animated: true,completion: nil)
}
func pass(name: String) {
del.text = name
}
}
说明:
在这一行let delegate:DataPass! = ViewController()
中,您将为不包含任何标签的委托变量创建another instance
。您需要在展示下一个控制器以使其正常工作的同时分配ViewController's instance
。