gpt4 book ai didi

swift - 在 UIviewcontroller 的按钮操作中使用 viewDidLoad 中的变量

转载 作者:行者123 更新时间:2023-11-30 12:11:13 26 4
gpt4 key购买 nike

我正在尝试让按钮根据按钮的文本显示警报。因此,在 View 确实加载时,我从数组中提取了一些随机值:

let ingredient1 = realBases[Int(arc4random_uniform(UInt32(realBases.count)))]

var ingredient2 = juices[Int(arc4random_uniform(UInt32(juices.count)))]
let indexOf2 = juices.index(of: ingredient2)
juices.remove(at: indexOf2!)
if ingredient2 == ingredient1 {
ingredient2 = ""
}

var ingredient3 = juices[Int(arc4random_uniform(UInt32(juices.count)))]
let indexOf3 = juices.index(of: ingredient3)
juices.remove(at: indexOf3!)
if ingredient3 == ingredient1 {
ingredient3 = ""
}

var ingredient4 = juices[Int(arc4random_uniform(UInt32(juices.count)))]
let indexOf4 = juices.index(of: ingredient4)
juices.remove(at: indexOf4!)
if ingredient4 == ingredient1 {
ingredient4 = ""
}

正如您所看到的,设置值后,该元素将从数组中删除以防止重复使用。

然后我为按钮指定这些名称:

btnO1.setTitle(newArray[0], for: UIControlState.normal)
btnO2.setTitle(newArray[1], for: UIControlState.normal)
btnO3.setTitle(newArray[2], for: UIControlState.normal)
btnO4.setTitle(newArray[3], for: UIControlState.normal)
btnO5.setTitle(newArray[4], for: UIControlState.normal)

现在我希望按钮显示特定的消息,具体取决于它们获取的名称。也就是说,如果一个按钮的名称为“燕麦牛奶”,那么当单击该按钮时,我希望在警报中显示有关燕麦的信息。

所以我有以下代码:

let ingredient1Text = UIAlertController.init(title: "", message: "", preferredStyle: UIAlertControllerStyle.alert)
ingredient1Text.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.default, handler:nil))

self.present(ingredient1Text, animated: true, completion: nil)

switch ingredient1 {
case "Oat Milk":
ingredient1Text.title = "Oat Milk"
ingredient1Text.message = oatMilkText
case "Soy Milk":
ingredient1Text.title = "Soy Milk"
ingredient1Text.message = soyMilkText
case "Almond Milk":
ingredient1Text.title = "Almond Milk"
ingredient1Text.message = almondMilkText
case "Cashew Milk":
ingredient1Text.title = "Cashew Milk"
ingredient1Text.message = cashewMilkText

我不能做的就是将该代码放入按钮操作中。这是因为变量fragment1在viewDidload()中,所以它无法识别该变量。我可以将这些变量放在 viewDidLoad 之外,但我不能,因为我在定义每个随机值后从数组中删除元素,显然这不会在顶层发生。

所以我被困住了。

最佳答案

您可以在操作中访问按钮的标题,如下所示:

@IBAction func myAction(_ sender: Any?) {
guard let button = sender as? UIButton else { return }
let buttonTitle = button.title(for: .normal)

...
}

关于swift - 在 UIviewcontroller 的按钮操作中使用 viewDidLoad 中的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46028486/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com