Swift 3.0委托协议不起作用
我在两个视图控制器中制作了委托协议。 但委托方法不会调用我的代码片段。 是什么原因。 我无法找到问题,请发布您的建议以重温此问题。
主视图控制器
class ViewController: UIViewController, testDelegateMethod { override func viewDidLoad() { super.viewDidLoad() let vw = testViewController() vw.delegateTest = self let push = self.storyboard?.instantiateViewController(withIdentifier: "testViewController") self.navigationController?.pushViewController(push!, animated: true) } func testMethod(value:String) { print("Hai", value) } }
子视图控制器
protocol testDelegateMethod { func testMethod(value:String) } class testViewController: UIViewController { var delegateTest : testDelegateMethod? override func viewDidLoad() { super.viewDidLoad() } @IBAction func actSubmit(_ sender: Any) { delegateTest?.testMethod(value: "Hello how are you!") } }
在viewdidLoad()
方法中更新这些更改
override func viewDidLoad() { super.viewDidLoad() if let push = self.storyboard?.instantiateViewController(withIdentifier: "testViewController") as? SelectionScreen { push.delegateTest = self } }
由于这一行你面临的问题
let vw = testViewController() vw.delegateTest = self
您已经创建了testViewController vw的实例,以及vw实例的Assigned委托
在下一行
let push = self.storyboard?.instantiateViewController(withIdentifier: "testViewController") self.navigationController?.pushViewController(push!, animated: true)
您正在创建testviewcontroller push的不同实例
不需要这个代码,
let vw = testViewController() vw.delegateTest = self
相反
let push testViewController = self.storyboard.instantiateViewController(withIdentifier: "testViewController") as! testViewController push.delegateTest = self self.navigationController?.pushViewController(push, animated: true)
这段代码片段没有意义。 您只需创建一个对象,但不会进一步使用它。 因此,请删除此代码段。
let vw = testViewController() vw.delegateTest = self
这样做:
override func viewDidLoad() { super.viewDidLoad() let pushVC = self.storyboard?.instantiateViewController(withIdentifier: "testViewController") as! testViewController pushVC.delegateTest = self self.navigationController?.pushViewController(pushVC, animated: true) }
我想,你把代码func testMethod(value:String) { print("Hai", value) }
放到viewDidLoad及上面let push = self.storyboard?.instantiateViewController(withIdentifier: "testViewController") self.navigationController?.pushViewController(push!, animated: true)
let vw = testViewController() // Your are doing wrong code vw.delegateTest = self
仅使用此
我希望它对你有用
let storyboard = UIStoryboard(name: "Main", bundle: nil) let push = storyboard.instantiateViewController(withIdentifier:"testViewController")as! testViewController push.delegateTest = self self.navigationController?.pushViewController(push, animated: true)
- 使用来自Parse.com的数据启用button – Swift
- 如何检测UITableView标题何时滚动到可见区域?
- 2500+架构armv7的重复符号 – Xcode 8
- 在从容器视图控制器添加/删除时,如何为子视图控制器设置动画?
- 在Xcode Interface Builder中 – 为什么编辑器中的选项—>排列菜单(包含发送到前面,发送到后面)常常被禁用?
- NSDateFormatter dateFromString返回不正确的date
- 你能从一个地址在Mapview中创build一个注解吗?
- UIActivityViewController排除所有的UIActivityCategoryAction
- 在iOS6中获取用户个人资料照片?