动态/以编程方式将IBAction分配给按钮

时间:2018-10-22 11:23:24

标签: ios swift ibaction

对于我的项目,我创建了一个排序菜单,该菜单以编程方式创建了水平滚动的按钮。但是我正在寻找将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。还有一个快速文件,用于水平排列菜单项。

2 个答案:

答案 0 :(得分:3)

标记是一种实现方法,但是最简单的方法可能是在每个标记上调用addTarget(_:action:for:)来设置其操作,例如

button.addTarget(button,
                 action: #selector(buttonFunctionThatDoesSomething:),
                 for: .touchUpInside) // or .primaryActionTriggered

第一个参数是要调用其选择器(第二个参数)的对象。 #selector()语法确实很挑剔。您可能需要阅读this SO answer来找出正确的调用方式。

答案 1 :(得分:0)

来自苹果文档https://developer.apple.com/library/archive/referencelibrary/GettingStarted/DevelopiOSAppsSwift/ImplementingACustomControl.html。 :

 button.addTarget(self, action: #selector(funcName), for: .touchUpInside)

然后:

 @objc func funcName()  {
       //do what u want in here
    }