我是新手,现在我正在学习代表。我想我已经做了正确的事,但它仍然没有用。
我正在做的是将数据从ViewController
传递到TestViewController
的ViewController:
protocol viewControllerDelegate: class {
func viewcontrollerdelegate(setviewcontrollerdelegate: ViewController)
}
class ViewController: UIViewController ,UITextFieldDelegate {
weak var delegate: viewControllerDelegate?
@IBAction func nextViewandDelegate(sender: AnyObject) {
self.delegate?.viewcontrollerdelegate(self)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "showTestSegue" {
if let testViewController = segue.destinationViewController as? TestViewController {
testViewController.address = address.text!
testViewController.phone = phone.text!
}
}
}
}
TestViewController:
class TestViewController: UIViewController {
var name: String?
var address: String?
var phone: String?
var trydelegate: String?
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let VC = storyboard.instantiateViewControllerWithIdentifier("viewcontroller") as! ViewController
VC.delegate = self
}
override func viewWillAppear(animated: Bool) {
addressLabel.text = address!
phoneLabel.text = phone!
trydelegateLabel.text = trydelegate //always nil here
}
}
extension TestViewController:viewControllerDelegate {
func viewcontrollerdelegate(setviewcontrollerdelegate: ViewController) {
self.trydelegate = setviewcontrollerdelegate.address.text!
}
}
我使用segue传递地址和电话,但效果很好。
但我对代表感到厌烦。任何人都可以帮我一点点吗?我知道这个问题对你来说有点容易。
非常感谢。
答案 0 :(得分:1)
在TestViewController
中的viewDidLoad
中,您创建的新对象vc
与调用prepareForSegue
的对象不同,这就是为什么它没有&#39}工作。
要解决此问题,请从viewDidLoad
删除代码:
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let vc = storyboard.instantiateViewControllerWithIdentifier("viewcontroller") as! ViewController
vc.delegate = self
在prepareForSegue
添加一行:
testViewController.phone = phone.text!
// New line
self.delegate = testViewController
这应该有所帮助。
答案 1 :(得分:0)
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "showTestSegue" {
if let testViewController = segue.destinationViewController as? TestViewController {
testViewController.address = address.text!
testViewController.phone = phone.text!
self.delegate = testViewController
self.delegate?.viewcontrollerdelegate(self)
}
}
}
删除@IBAction func nextViewandDelegate(sender:AnyObject)并更改该prepareforsegue
我修好了......它现在正在工作,但我不知道为什么