[英]issue passing data back to first view controller with delegate and protocol (Swift)
所以我要做的是在我關閉它時將一個 String 和一個 Int 從一個 ViewController (NewCellViewController) 傳遞回前一個 (SecondScreenViewController)。 我在 SecondScreenViewController 的方法中添加了一個打印語句,它應該接收此數據,但它沒有打印,所以我猜該方法從未運行過。 這是我的代碼(刪除了一些內容以僅包含相關內容):
SecondScreenViewController:
import UIKit
protocol DataDelegate {
func insertEvent(eventString: String, pos: Int)
}
class SecondScreenViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, DataDelegate {
var eventNames = ["event1", "event2", "event3"]
override func viewDidLoad() {
super.viewDidLoad()
advance()
}
//DataDelegate methods
func insertEvent(eventString: String, pos: Int)
{
print("if this prints, it worked")
if pos == -1
{
eventNames.append(eventString)
}
else
{
eventNames.insert(eventString, at: pos)
}
}
@objc func advance()
{
let vc = NewCellViewController(nibName: "NewCellViewController", bundle: nil)
vc.delegate = self
present(vc, animated: true, completion: nil)
}
}
新CellViewController:
import UIKit
class NewCellViewController: UIViewController {
var delegate:DataDelegate?
@IBOutlet var addEventName: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
}
@IBAction func addItem() {
insertNewEvent()
dismiss(animated: true, completion: nil)
}
func insertNewEvent()
{
let eventName = addEventName!.text
delegate?.insertEvent(eventString: eventName!, pos: -1) //add different positions
}
}
我使用了與您相同的controller
名稱,只是為了讓您更好地理解。
import UIKit
class SecondScreenViewController: UIViewController {
var eventNames = ["event1", "event2", "event3"]
override func viewDidLoad() {
super.viewDidLoad()
//advance()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
advance()
}
private func advance() {
// Dont forget to add `Storyboard ID` as "NewCellViewController" on your Main.storyboard.
// See the image attached below.
if let vc = self.storyboard?.instantiateViewController(identifier: "NewCellViewController") as? NewCellViewController {
vc.delegate = self
present(vc, animated: true)
}
}
}
// Better this way.
extension SecondScreenViewController: DataDelegate {
func insertEvent(eventString: String, pos: Int) {
print(eventString, pos)
}
}
import UIKit
// Better to create protocols here.
protocol DataDelegate: class {
func insertEvent(eventString: String, pos: Int)
}
class NewCellViewController: UIViewController {
weak var delegate: DataDelegate?
@IBOutlet var addEventName: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
}
@IBAction func addItem() {
insertNewEvent()
dismiss(animated: true)
}
private func insertNewEvent() {
delegate?.insertEvent(eventString: "your text", pos: -1)
}
}
希望這可以幫助。
您可以嘗試在第一個 VC 中使用 segue 來推送第二個 VC 並彈出第二個 VC 並返回到第一個 VC。 這可能會幫助您與委托人合作。 您還可以使用 UserDefaults 來傳遞和同步這些值。
根據您想要傳遞的具體內容,您可以使用用戶默認值。 很多人不推薦,但我覺得對於簡單的數據,它確實快速有效
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.