微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

快速地将数据从一个ViewController传递到另一个ViewController

如何解决快速地将数据从一个ViewController传递到另一个ViewController

我只想在两个ViewController之间传输一些数据,并且还编写了一些代码。但是,如果我更新tableView,则不会在tableView上显示用户提供的数据。谁能帮我吗?

import UIKit

导入CoreData

AddNewRecipeViewController类:UIViewController,UITableViewDelegate,UITableViewDataSource {

private let reuseIdentifer = "IngredientCell"
let pressGesture = UILongPressGestureRecognizer()
let titleLabel = UILabel()
let tf_one = UITextField()
let tf_two = UITextField()
let tableView = UITableView()
let submitButton = UIButton()

let newButton = UIButton()

var name_array = [String]()
var unit_array = [String]()
var quantity_array = [String]()

let recipeId = Int.random(in: 0...5000)

override func viewDidLoad() {
    super.viewDidLoad()
    view.backgroundColor = .white
    createViewControllerItems()
}
@objc func refresh(){
    print(name_array)
    self.tableView.reloadData()
}
override func touchesBegan(_ touches: Set<UITouch>,with event: UIEvent?) {
    self.view.endEditing(true)
}

@objc func dismissKeyboard() {
    view.endEditing(true)
}

func createViewControllerItems() {
// - MARK: Titel
    titleLabel.text = "Neues Rezept"
    titleLabel.textColor = .black
    titleLabel.textAlignment = .center
    titleLabel.font = UIFont(name: "Bradley Hand",size: 24)
    
    view.addSubview(titleLabel)
    titleLabel.translatesAutoresizingMaskIntoConstraints = false
    titleLabel.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
    titleLabel.topAnchor.constraint(equalTo: view.topAnchor,constant: 30).isActive = true
    titleLabel.widthAnchor.constraint(equalToConstant: 200).isActive = true
    titleLabel.heightAnchor.constraint(equalToConstant: 40).isActive = true
    
    newButton.setTitle("test",for: UIControl.State.normal)
    newButton.setTitleColor(.black,for: UIControl.State.normal)
    newButton.addTarget(self,action: #selector(refresh),for: .touchUpInside)
    view.addSubview(newButton)
    newButton.translatesAutoresizingMaskIntoConstraints = false
    newButton.leftAnchor.constraint(equalTo: view.leftAnchor,constant: 30).isActive = true
    newButton.topAnchor.constraint(equalTo: view.topAnchor,constant: 30).isActive = true
    newButton.widthAnchor.constraint(equalToConstant: 40).isActive = true
    newButton.heightAnchor.constraint(equalToConstant: 40).isActive = true
    
// - MARK: Überschrift
    
    tf_one.placeholder = "Name"
    tf_one.borderStyle = .roundedRect
    tf_one.keyboardType = .default
    tf_one.spellCheckingType = .yes
    tf_one.smartInsertDeleteType = .yes
    tf_one.autocorrectionType = .yes
    tf_one.autocapitalizationType = .sentences
    
    view.addSubview(tf_one)
    tf_one.translatesAutoresizingMaskIntoConstraints = false
    tf_one.leftAnchor.constraint(equalTo: view.leftAnchor,constant: 15).isActive = true
    tf_one.topAnchor.constraint(equalTo: view.topAnchor,constant: 100).isActive = true
    tf_one.widthAnchor.constraint(equalToConstant: 270).isActive = true
    tf_one.heightAnchor.constraint(equalToConstant: 34).isActive = true
    
// - MARK: Anzahl Portionen
    
    tf_two.placeholder = "Anzahl"
    tf_two.borderStyle = .roundedRect
    tf_two.keyboardType = .decimalPad
    
    view.addSubview(tf_two)
    tf_two.translatesAutoresizingMaskIntoConstraints = false
    tf_two.topAnchor.constraint(equalTo: view.topAnchor,constant: 100).isActive = true
    tf_two.leftAnchor.constraint(equalTo: tf_one.rightAnchor,constant: 3).isActive = true
    tf_two.widthAnchor.constraint(equalToConstant: 70).isActive = true
    tf_two.heightAnchor.constraint(equalToConstant: 34).isActive = true
   
// - MARK: Table View
    tableView.delegate = self
    tableView.dataSource = self
    tableView.register(IngredientCell.self,forCellReuseIdentifier: reuseIdentifer)
    tableView.rowHeight = 55
    
    view.addSubview(tableView)
    tableView.translatesAutoresizingMaskIntoConstraints = false
    tableView.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true
    tableView.rightAnchor.constraint(equalTo: view.rightAnchor).isActive = true
    tableView.bottomAnchor.constraint(equalTo: view.bottomAnchor,constant: -100).isActive = true
    tableView.topAnchor.constraint(equalTo: tf_one.bottomAnchor,constant: 10).isActive = true
    
    
// - MARK: Bestätigen
    submitButton.layer.cornerRadius = 20
    submitButton.clipsToBounds = true
    submitButton.backgroundColor = .lightGray
    submitButton.setTitle("ok",for: UIControl.State.normal)
    submitButton.setTitleColor(.white,for: UIControl.State.normal)
    submitButton.titleLabel?.font = UIFont(name: "Chalkduster",size: 24)
    submitButton.addTarget(self,action: #selector(save),for: .touchUpInside)
    
    view.addSubview(submitButton)
    submitButton.translatesAutoresizingMaskIntoConstraints = false
    submitButton.rightAnchor.constraint(equalTo: view.rightAnchor,constant: -30).isActive = true
    submitButton.topAnchor.constraint(equalTo: view.topAnchor,constant: 30).isActive = true
    submitButton.widthAnchor.constraint(equalToConstant: 40).isActive = true
    submitButton.heightAnchor.constraint(equalToConstant: 40).isActive = true
    
// - MARK: Add Gesture
    pressGesture.addTarget(self,action: #selector(pressAction))
    
    view.addGestureRecognizer(pressGesture)

}

@objc func pressAction() {
    let generator = UIImpactFeedbackGenerator(style: .heavy)
    generator.impactOccurred()
    let vc: AddNewIngredientViewController!
    vc = AddNewIngredientViewController()
    vc.modalPresentationStyle = .automatic
    self.present(vc,animated: true)
}

@objc func save() {
    //save befor dismiss
    dismiss(animated: true,completion: nil)
    /*
    guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else {
        return
    }
    let context = appDelegate.persistentContainer.viewContext
    let entityName = "Recipes"
    guard let newEntity = NSEntityDescription.entity(forEntityName: entityName,in: context) else {
        return
    }
    let newRecipe = NSManagedobject(entity: newEntity,insertInto: context)
    let name = tf_one.text
    let id = recipeId
    let category = 1
    let persons = 2

    newRecipe.setValue(name,forKey: "name")
    newRecipe.setValue(id,forKey: "id")
    newRecipe.setValue(category,forKey: "category")
    newRecipe.setValue(persons,forKey: "persons")

    do {
        try context.save()
        print("Gespeichert!")
        let vc: ViewController!
        vc = ViewController()
        vc.modalPresentationStyle = .fullScreen
        self.present(vc,animated: false)
    } catch {
        print(error)
    }*/
}
func tableView(_ tableView: UITableView,numberOfRowsInSection section: Int) -> Int {
    print(name_array.count)
    return name_array.count
}

func tableView(_ tableView: UITableView,cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: reuseIdentifer,for: indexPath) as! IngredientCell
    cell.nameLabel.text = name_array[indexPath.row]
    cell.descriptionLabel.text = "text"
    cell.personsLabel.text = "text"
    return cell
}

func tableView(_ tableView: UITableView,commit editingStyle: UITableViewCell.EditingStyle,forRowAt indexPath: IndexPath) {
    if editingStyle == .delete {
        guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else {
            return
        }
        let context = appDelegate.persistentContainer.viewContext
        let entityName = "/ENTRY/"
        
        let request = NSFetchRequest<NSFetchRequestResult>(entityName: entityName)
        do {
            let results = try context.fetch(request)
            
            guard results.count > 0 else {
                return
            }
            if let deleteEntity = results[indexPath.row] as? NSManagedobject {
                context.delete(deleteEntity) //Das Entity ist hier nur markiert als gelöscht,für evt arbeiten am Item
                if context.hasChanges {
                    do {
                        try context.save()
                        print("Datensatz gelöscht!")
                        let vc: ViewController!
                        vc = ViewController()
                        vc.modalPresentationStyle = .fullScreen
                        self.present(vc,animated: false)
                    } catch {
                        print(error)
                    }
                }
            }
        } catch {
            print(error)
        }
    }
}

}

导入UIKit 导入CoreData

AddNewIngredientViewController类:UIViewController {

let viewExample = UIView()
let titleLabel = UILabel()
let tf_one = UITextField()
let unitTicker = UISegmentedControl()
let unitLabel = UILabel()
let slider = UiSlider()
let submitButton = UIButton()

override func viewDidLoad() {
    super.viewDidLoad()
    view.backgroundColor = UIColor.white.withAlphaComponent(0)
    createViewControllerItems()
}

override func touchesBegan(_ touches: Set<UITouch>,with event: UIEvent?) {
    self.view.endEditing(true)
}

@objc func dismissKeyboard() {
    view.endEditing(true)
}

func createViewControllerItems() {
// - MARK: View
    viewExample.backgroundColor = .white
    viewExample.layer.cornerRadius = 15
    viewExample.clipsToBounds = true
    view.addSubview(viewExample)
    viewExample.translatesAutoresizingMaskIntoConstraints = false
    viewExample.centerYAnchor.constraint(equalTo: view.centerYAnchor,constant: -200).isActive = true
    viewExample.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
    viewExample.widthAnchor.constraint(equalToConstant: 330).isActive = true
    viewExample.heightAnchor.constraint(equalToConstant: 350).isActive = true
    
// - MARK: Titel
    titleLabel.text = "Zutat hinzufügen"
    titleLabel.textColor = .black
    titleLabel.textAlignment = .center
    titleLabel.font = UIFont(name: "Chalkduster",constant: 50).isActive = true
    titleLabel.widthAnchor.constraint(equalToConstant: 250).isActive = true
    titleLabel.heightAnchor.constraint(equalToConstant: 40).isActive = true
    
// - MARK: Überschrift
    
    tf_one.placeholder = "Name"
    tf_one.borderStyle = .roundedRect
    tf_one.keyboardType = .default
    tf_one.spellCheckingType = .yes
    tf_one.smartInsertDeleteType = .yes
    tf_one.autocorrectionType = .yes
    tf_one.autocapitalizationType = .sentences
    
    view.addSubview(tf_one)
    tf_one.translatesAutoresizingMaskIntoConstraints = false
    tf_one.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
    tf_one.topAnchor.constraint(equalTo: view.topAnchor,constant: 100).isActive = true
    tf_one.widthAnchor.constraint(equalToConstant: 310).isActive = true
    tf_one.heightAnchor.constraint(equalToConstant: 34).isActive = true
    
// - MARK: Unit Ticker
    unitTicker.insertSegment(withTitle: "ml",at: 0,animated: true)
    unitTicker.insertSegment(withTitle: "mg",at: 1,animated: true)
    unitTicker.insertSegment(withTitle: "unit",at: 2,animated: true)
    unitTicker.addTarget(self,action: #selector(updateLabel),for: UIControl.Event.allEvents)
    view.addSubview(unitTicker)
    unitTicker.translatesAutoresizingMaskIntoConstraints = false
    unitTicker.topAnchor.constraint(equalTo: view.topAnchor,constant: 150).isActive = true
    unitTicker.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true

// - MARK: Slider
    slider.maximumValue = 10
    slider.addTarget(self,for: UIControl.Event.allEvents)
    view.addSubview(slider)
    slider.translatesAutoresizingMaskIntoConstraints = false
    slider.topAnchor.constraint(equalTo: view.topAnchor,constant: 200).isActive = true
    slider.widthAnchor.constraint(equalToConstant: 310).isActive = true
    slider.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
    
// - MARK: Bestätigen
    submitButton.layer.cornerRadius = 20
    submitButton.clipsToBounds = true
    submitButton.backgroundColor = .lightGray
    submitButton.setTitle("ok",for: .touchUpInside)
    
    view.addSubview(submitButton)
    submitButton.translatesAutoresizingMaskIntoConstraints = false
    submitButton.centerXAnchor.constraint(equalTo: view.centerXAnchor,constant: 100).isActive = true
    submitButton.topAnchor.constraint(equalTo: slider.bottomAnchor,constant: 50).isActive = true
    submitButton.widthAnchor.constraint(equalToConstant: 40).isActive = true
    submitButton.heightAnchor.constraint(equalToConstant: 40).isActive = true
}

@objc func updateLabel() {
    unitLabel.textAlignment = .center
    if unitTicker.selectedSegmentIndex == 0{
        unitLabel.text = "\(Int(slider.value)) ml"
        slider.maximumValue = 1000
    }else if unitTicker.selectedSegmentIndex == 1{
        unitLabel.text = "\(Int(slider.value)) mg"
        slider.maximumValue = 1000
    }else if unitTicker.selectedSegmentIndex == 2{
        unitLabel.text = "\(Int(slider.value)) unit"
        slider.maximumValue = 10
    }
    view.addSubview(unitLabel)
    unitLabel.translatesAutoresizingMaskIntoConstraints = false
    unitLabel.topAnchor.constraint(equalTo: view.topAnchor,constant: 230).isActive = true
    unitLabel.widthAnchor.constraint(equalToConstant: 310).isActive = true
    unitLabel.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
}
@objc func save() {
    let viewController = AddNewRecipeViewController()
    viewController.name_array.append(tf_one.text!)
    print(viewController.name_array)
    dismiss(animated: true,completion: nil)
}

}

谢谢! 汤姆

解决方法

您可以使用委托方法或NSNotificaton在两个viewController之间传递数据。有关更多信息,请访问NSNotification:https://developer.apple.com/documentation/foundation/nsnotification

对于委托方法,您可以检查https://medium.com/@jamesrochabrun/implementing-delegates-in-swift-step-by-step-d3211cbac3ef

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。