将数据从SearchBar传递到UILabel

问题描述 投票:0回答:2

如何将数据从搜索栏传递到其他视图控制器中的UILabel

Passing Data between View Controllers我已经在堆栈上尝试了多个问题,但是它不起作用,或者模拟器最终对我崩溃了

class FirstVC: UIViewController, DataEnteredDelegate {

    @IBOutlet weak var label: UILabel!

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "showSecondViewController" {
            let secondViewController = segue.destination as! SecondVC
            secondViewController.delegate = self
        }
    }

    func userDidEnterInformation(info: String) {
        label.text = info
    }
}



 // protocol used for sending data back

protocol DataEnteredDelegate: class {
    func userDidEnterInformation(info: String)
}

class SecondVC: UIViewController {

    // making this a weak variable so that it won't create a strong reference cycle
    weak var delegate: DataEnteredDelegate? = nil

    @IBOutlet weak var searchBar: UISearchBar!

    @IBAction func sendTextBackButton(sender: AnyObject) {

        // call this method on whichever class implements our delegate protocol
        delegate?.userDidEnterInformation(info: searchBar.text!)

        // go back to the previous view controller
        _ = self.navigationController?.popViewController(animated: true)
    }
}
ios swift xcode search label
2个回答
0
投票
我在您的代码中没有发现任何可疑的内容,这些可导致应用程序崩溃。同时,对于视图控制器之间的数据传输,我们可以使用委托和NotificationCenter。下面的代码使用NotificationCenter

let kStringTransfer = "StringTransferNotification" class FirstViewController: UIViewController, DataEnteredDelegate { @IBOutlet weak var textField: UITextField! override func viewDidLoad() { super.viewDidLoad() NotificationCenter.default.addObserver(self, selector: #selector(setString(notify:)), name: NSNotification.Name(rawValue: kStringTransfer), object: nil) } func getSecondVC() { if let second = self.storyboard?.instantiateViewController(withIdentifier: "Second") as? ViewController { self.navigationController?.pushViewController(second, animated: true) } } @IBAction func searchBarBtn(_ sender: Any) { //go to search view controller getSecondVC() } @objc func setString(notify: Notification) { //set search bar string to text field textField.text = notify.object as? String } } class SecondViewController: UIViewController, UISearchBarDelegate { @IBOutlet weak var searchBar: UISearchBar! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. searchBar.delegate = self } @IBAction func goBackBtn(_ sender: Any) { NotificationCenter.default.post(name: NSNotification.Name(rawValue: kStringTransfer), object: searchBar.text) self.navigationController?.popViewController(animated: true) } }


0
投票
[当我需要在两个viewController之间传递很小的值时,我不使用委托,只需在第二个视图中创建一个变量并像这样传递。

override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if (segue.identifier == "showView") { let vc = segue.destination as! secondViewController vc.stringTemp = "My string" } }

© www.soinside.com 2019 - 2024. All rights reserved.