ios - 如何在自定义表格 View 单元格之间传递数据?

标签 ios swift tableview custom-cell

我有两个自定义 TableView (不是 TableView Controller )

细胞。我想从 MainViewcontroller

选择第二个单元格

并选择

单元格信息的标题和价格作为

传递给第二个 View

DetailViewController 的第一个和第二个索引标签。

这是我的 MainViewController.swift

编辑:这是答案

import UIKit

class MainViewController: UIViewController, UITableViewDataSource,      UITableViewDelegate,
UICollectionViewDelegate, UICollectionViewDataSource,    UICollectionViewDelegateFlowLayout {

@IBOutlet weak var searchBar: UISearchBar!
@IBOutlet weak var mainTableView: UITableView!

var imageNames = [ImageNames]()
var searchFoods: [String]!
var priceFood: [Double]!
var searching = false


override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    self.tabBarController?.tabBar.isHidden = false
}

override func viewDidLoad() {
    super.viewDidLoad()

    self.navigationController?.navigationBar.isHidden = true
    let foodCell = Food(name: ["Hamburger big mac",
                               "Patates",
                               "Whopper",
                               "Steakhouse"], price: [15.0, 20.0, 25.0, 30.0])

   searchBar.delegate = self
   searchFoods = foodCell.name
   priceFood = foodCell.price



    imageNames = [
        ImageNames(name: "images"),
        ImageNames(name: "unnamed"),
        ImageNames(name: "unnamed")
    ]

}

func numberOfSections(in tableView: UITableView) -> Int {
    return 2
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

    return section == 0 ? 1 : searchFoods.count
    //        return section == 0 ? 1 : foodNames.count

}

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    return indexPath.section == 0 ? 130 : 65
}

func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
    return indexPath.section == 0 ? 100 : 65
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    if indexPath.section == 0 {
        let cell = tableView.dequeueReusableCell(withIdentifier: "MainFoodTableViewCell", for: indexPath) as! MainFoodTableViewCell

        cell.mainFoodCollectionView.delegate = self
        cell.mainFoodCollectionView.dataSource = self
        cell.mainFoodCollectionView.reloadData()
        cell.mainFoodCollectionView.tag = indexPath.row
        return cell

    } else {

        let cell = tableView.dequeueReusableCell(withIdentifier: "CellForFood", for: indexPath) as! MainFoodTitleTableViewCell

        cell.titleLabel?.text = searchFoods[indexPath.row]
        cell.priceLabel?.text = priceFood[indexPath.row].description

        return cell
    }

}

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "cellForFoodSegue" {
        if let destinationViewController = segue.destination as? DetailViewController
        {
            let indexPath = self.mainTableView.indexPathForSelectedRow!

            var foodNameArray: [String]
            var foodPriceArray: [Double]

            foodNameArray = [searchFoods[indexPath.row]]
            foodPriceArray = [priceFood[indexPath.row]]

            destinationViewController.detailFoodName = foodNameArray
            destinationViewController.detailFoodPrice = foodPriceArray

        }

    }
}

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return  imageNames.count
}

//MARK:- collection view cell size
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    let width = UIScreen.main.bounds.width
    return CGSize(width: width, height: 130)
}

//MARK:- //collection view cell data
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "MainFoodCollectionViewCell", for: indexPath) as! MainFoodCollectionViewCell
    let img = imageNames[indexPath.row]
    cell.mainFoodImage.image = UIImage(named: img.name)
    return cell
}

//MARK:- SearchBar 数据 扩展 MainViewController : UISearchBarDelegate {

func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) {
    self.searchBar.showsCancelButton = true
    mainTableView.reloadData()
}

func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
    mainTableView.reloadData()
    searchBar.showsCancelButton = false
    searchBar.text = ""
    searchBar.resignFirstResponder()

}

func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
    searchFoods = searchText.isEmpty ? searchFoods : searchFoods.filter { (item: String) -> Bool in
        return item.range(of: searchText, options: .caseInsensitive, range: nil, locale: nil) != nil
    }

    mainTableView.reloadData()
}
}

编辑:这是我的 DetailViewController

import UIKit

class DetailViewController: UIViewController {

@IBOutlet weak var foodTitle: UILabel!
@IBOutlet weak var foodSubTitle: UILabel!
@IBOutlet weak var foodPiece: UILabel!
@IBOutlet weak var foodPrice: UILabel!
@IBOutlet weak var drinkPicker: UITextField!
@IBOutlet weak var menuPieceStepper: UIStepper!

var drinkPickerView = UIPickerView()    
var selectDrinkType: [String] = []
var detailFoodName : [String] = []
var detailFoodPrice : [Double] = [0.0]



let foods = Food(name: ["Hamburger big mac",
                           "Patates",
                           "Whopper",
                           "Steakhouse"], price: [15.0, 20.0, 25.0, 30.0])


@IBAction func foodPieceStepper(_ sender: Any) {
}

@objc func foodPieceChangeStepper() {
    let res = menuPieceStepper.value + foods.price.first!
    foodPrice.text = "\(res)"
}

@IBAction func addBasket(_ sender: Any) {

        let destinationVC = MyCartViewController()

        destinationVC.fromDetailFoodNames = foods.name
        destinationVC.fromDetailFoodPrices = foods.price
    dismiss(animated: true)

}

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
   if(segue.identifier == "addToCartSegue") {
        if let addToCartVC = segue.destination as? MyCartViewController      {


            addToCartVC.fromDetailFoodNames = [foodTitle.text]
            addToCartVC.fromDetailFoodPrices = foods.price

    }
   }
}

override func viewDidLoad() {
    super.viewDidLoad()

    menuPieceStepper.value = 0.0
    menuPieceStepper.minimumValue = 0.0
    menuPieceStepper.maximumValue = 30.0
    menuPieceStepper.stepValue = foods.price.first!
    menuPieceStepper.addTarget(self, action:    #selector(foodPieceChangeStepper), for: .valueChanged)

    drinkPickerView.delegate = self
    drinkPicker.inputView = drinkPickerView
    selectDrinkType = ["Ayran", "Kola", "Su", "Fanta", "Şalgam",   "Sprite"]

    foodTitle.text = detailFoodName.description
    foodPrice.text = detailFoodPrice.description

    self.navigationController?.navigationItem.title = "Sipariş Detayı"
    let tapGesture = UITapGestureRecognizer(target: self, action:      #selector(self.dismissKeyboard (_:)))
    self.view.addGestureRecognizer(tapGesture)
}
@objc func dismissKeyboard (_ sender: UITapGestureRecognizer) {
   drinkPicker.resignFirstResponder()
}

override func viewWillAppear(_ animated: Bool) {
    self.navigationController?.navigationBar.isHidden = false

}

override func viewWillDisappear(_ animated: Bool) {
    self.navigationController?.navigationBar.isHidden = true
}
}

extension DetailViewController: UIPickerViewDelegate,     UIPickerViewDataSource {
func numberOfComponents(in pickerView: UIPickerView) -> Int {
    return 1
}

func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
    return selectDrinkType.count
}

func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
    return selectDrinkType[row]
}

func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
    let selectedDrink = selectDrinkType[row]
    drinkPicker.text = selectedDrink
}

}

最佳答案

你不是在找prepare(for segue: sender:)吗?方法? Usually you need to bind a cell prototype to a detail view with a segue, and when the cell is selected the segue is followed just after that method is called to prepare data injection to the detail view.

关于ios - 如何在自定义表格 View 单元格之间传递数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54872552/

相关文章:

ios - MKMapView如何根据用户方向旋转导航图片?

ios - 在 Swift 中的 TableView 和另一个 ViewController 之间传递数据

Xcode swift : My unwind segue doesn't add to my tableView

ios - 选择表sqlite ios中的数据记录只返回一个对象

ios - 如何在 Swift 的 TableViewController 中向自动后退按钮添加 Action

ios - 调用 NSMutableAttributedString 的子类中的追加时应用程序崩溃

swift - tvOS隐藏时间栏,同时不丢失音频菜单?

ios - Xcode 7 垂直 ScrollView 问题

ios - Swift iOS 以编程方式 RTL 我的应用程序的布局

swift - 如何在swift中将委托(delegate)值添加到tableview