gpt4 book ai didi

ios - 使用委托(delegate)传递变量

转载 作者:行者123 更新时间:2023-11-28 13:18:14 24 4
gpt4 key购买 nike

我一直在竭尽全力试图让这个“委托(delegate)”的东西在 Swift 中为我正在开发的应用程序工作。

我有两个文件:CreateEvent.swiftContactSelection.swift,前者调用后者。

CreateEvent 的内容是:

class CreateEventViewController: UIViewController, ContactSelectionDelegate {

/...

var contactSelection: ContactSelectionViewController = ContactSelectionViewController()

override func viewDidLoad() {
super.viewDidLoad()

/...

contactSelection.delegate = self
}


func updateInvitedUsers() {
println("this finally worked")
}

func inviteButton(sender: AnyObject){
invitedLabel.text = "Invite"
invitedLabel.hidden = false
toContactSelection()
}

/...

func toContactSelection() {
let contactSelection = self.storyboard?.instantiateViewControllerWithIdentifier("ContactSelectionViewController") as ContactSelectionViewController
contactSelection.delegate = self
self.navigationController?.pushViewController(contactSelection, animated: true)
}

ContactSelection 的内容是:

protocol ContactSelectionDelegate {
func updateInvitedUsers()
}

class ContactSelectionViewController: UITableViewController {

var delegate: ContactSelectionDelegate?

override func viewDidLoad() {
super.viewDidLoad()

self.delegate?.updateInvitedUsers()

}

override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {

// Stuff

self.delegate?.updateInvitedUsers()

}
}

我做错了什么?我还是新手,并不完全了解这个主题,但在搜索互联网后,我似乎找不到答案。我使用导航栏中可用的 Back 按钮返回到我的 CreateEvent View 。

最佳答案

var contactSelection: ContactSelectionViewController = ContactSelectionViewController()

这是直接实例化一个 View Controller ,并且永远不会使用该值。由于看起来您正在使用 Storyboard ,这不是一个好主意,因为不会连接任何 socket ,并且您会遇到可选的展开崩溃。您设置了这个 View Controller 的委托(delegate),但这无关紧要,因为它没有被使用。

这也不是一个好主意,因为如果你进行多次推送,你将重复使用同一个 View Controller ,这最终会导致错误,因为你将拥有以前使用的遗留状态,这可能会给你带来意想不到的结果。最好每次都创建一个新的 View Controller 来推送。

在您的代码中,您正在从 Storyboard 中创建一个全新的 contactSelection 并在不设置委托(delegate)的情况下推送它。

您需要在要推送到导航堆栈的实例上设置委托(delegate)。

在委托(delegate)方法中传回可用于提取值的引用也很有帮助,而不是像您正在做的那样依赖 var 中的单独引用。

所以,我会执行以下操作:

  • 删除 var contactSelection
  • 在推送新的 contactSelection 对象之前添加委托(delegate)
  • 将委托(delegate)方法签名更改为:

    protocol ContactSelectionDelegate {
    func updateInvitedUsers(contactSelection:ContactSelectionViewController)
    }
  • 将您的委托(delegate)调用更改为此:

    self.delegate?.updateInvitedUsers(self)

关于ios - 使用委托(delegate)传递变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27938111/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com