【发布时间】:2018-10-22 11:23:24
【问题描述】:
对于我的项目,我创建了一个排序菜单,它以编程方式创建水平滚动的按钮。但是,我正在寻找将 IBAction(特别是写入 Firebase 数据库的操作)动态分配给这些按钮的方法…… 标记按钮和使用条件会起作用吗?
我的代码是
Food.swift - 每个菜单项的属性集
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 快速
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)
}
}
}
我可以添加到 Food.swift,
var buttonTag = ""
然后将标签分配给单个按钮。 在 UICollectionCell.swift 中,附加标签。使用 If...else... 条件将标签与单个 IBAction {ref?.child...")
匹配谢谢大家!!!
ps.还有另一个用于水平排列菜单项的 swift 文件..
【问题讨论】:
-
您应该考虑在按钮上使用
addTarget(_ target: Any?, action: Selector, for controlEvents: UIControl.Event)方法。 -
顾名思义,
Interface Builder Action仅适用于IB。只需添加一个目标。