For my project, I have created an ordering menu that programmatically creates buttons that scroll horizontally. However I am looking for ways to assign IBAction - specially action to write to Firebase database - to those buttons dynamically... Would tagging the buttons and using conditionals work?
My codes are
Food.swift - properties sets of each menu item
class Food
{
var title = ""
var featuredImage: UIImage
var color: UIColor
init(title: String, featuredImage: UIImage, color: UIColor)
{
self.title = title
self.featuredImage = featuredImage
self.color = color
}
static func fetchFoods() -> [Food]
{
return [
Food(title: " Biscuits", featuredImage: UIImage(named: "f1")!, color: UIColor(red: 63/255.0, green: 71/255.0, blue: 80/255.0, alpha: 0.6)),
Food(title: " Sandwich", featuredImage: UIImage(named: "f2")!, color: UIColor(red: 63/255.0, green: 71/255.0, blue: 80/255.0, alpha: 0.6)),
Food(title: " Veg Sandwich", featuredImage: UIImage(named: "f3")!, color: UIColor(red: 63/255.0, green: 71/255.0, blue: 80/255.0, alpha: 0.6)),
]
}
}
UICollectionCell swift
import UIKit
class FoodCollectionViewCell: UICollectionViewCell {
@IBOutlet weak var featuredImageView: UIImageView!
@IBOutlet weak var backgroundColorView: UIView!
@IBOutlet weak var foodButton: UIButton!
var food: Food? {
didSet {
self.updateUI()
}
}
private func updateUI()
{
if let food = food {
featuredImageView.image = food.featuredImage
backgroundColorView.backgroundColor = food.color
foodButton.setTitle("\(food.title)", for: .normal)
} else {
featuredImageView.image = nil
backgroundColorView.backgroundColor = nil
foodButton.setTitle("", for: .normal)
}
}
}
Can I add to Food.swift,
var buttonTag = ""
then assign tag to individual button. At UICollectionCell.swift, append tag. Using If...else... conditionals to match tag to individual IBAction {ref?.child...")
Thanks everyone!!!
ps.There is another swift file for arranging the menu items horizontally..