单击按钮将项目添加到另一个视图控制器表视图

时间:2019-06-29 10:02:44

标签: ios arrays swift uitableview delegates

我有一个名为ListViewController的视图控制器,另一个名为AddFoodViewController。在ListViewController中,用户可以将自己的食材添加到以表格视图显示的食品杂货清单中。当用户转到AddFoodViewController时,用户应该能够单击显示为“添加到列表”的按钮,该按钮会将Ingrediets数组(已在表格视图中显示)添加到杂货店列表中。我对此很陌生,所以我想知道是否有人可以提供帮助?我已经成功地使ListViewController正常工作,但是我不确定如何将AddFoodViewController中的成分数组添加到以前的ListViewController中。

class AddFoodViewController: UIViewController, UITableViewDataSource, UITableViewDelegate{


@IBOutlet weak var FoodTableView: UITableView!
@IBOutlet weak var sendFoodBtn: UIButton!

//array of food
let array = ["1 Salad", "3oz Chicken", "2 Tomatoes", "2 Cucumbers"]
let category = ""

override func viewDidLoad() {
        super.viewDidLoad()
}


//display array in table view
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 1
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return(array.count)
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let foodCell = UITableViewCell(style: UITableViewCell.CellStyle.default, reuseIdentifier: "foodCell")
        foodCell.textLabel?.text = array[indexPath.row]
        foodCell.backgroundColor = .clear
        foodCell.textLabel?.textColor = .darkGray
        foodCell.textLabel?.font = UIFont(name: (foodCell.textLabel?.font.fontName)!, size:17)
        return foodCell

    }


//button that is supposed to add all ingredients to the ListViewController
 @IBAction func addOnClick(_ sender: Any) {


}


override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if(segue.identifier == "toList"){
       let vc = (segue.destination as! ListViewController)
       vc.category = array
           }
    }
}

1 个答案:

答案 0 :(得分:0)

将数据传递到先前的视图控制器可以通过委托模式来实现,首先,在AddFoodViewController中声明一个协议,然后在视图控制器中定义一个委托属性。

// AddFoodViewController.swift
protocol AddFoodViewControllerDelegate {
    func addIngredient(array: [String])
}

class AddFoodViewController: UIViewController {
  ...
  var delegate: AddFoodViewControllerDelegate?

  // MARK: add function
  func actionAdd() {
    delegate?addIngredient(array)
  }
  ...
}

回到您的ListViewController,找到AddFoodViewController的segue目标视图控制器(记住在情节提要中分配其类名),然后将委托分配给self。

// ListViewController.swift
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    ...
    let vc = segue.destination as? AddFoodViewController
    vc?.delegate = self
    ...
}

// in the same file, implement delegate method here
extension ListViewController: AddFoodViewControllerDelegate {
    func addIngredient(array: [String]) {
        items += array
        // do table reload or something
    }
}