在UiviewController中的按钮操作中使用ViewDidload中的变量



我试图根据按钮的文字使按钮显示一个警报。因此,在视图中加载了我有一些从数组中拉出的随机值:

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

我不能做的是将该代码放在按钮操作中。这是因为变量成分位在ViewDidload()中,因此它无法识别变量。我可以将这些变量放在ViewDidload之外,但是我不能将这些变量在定义每个随机值后从数组中删除元素,显然这不能在最高级别发生。

所以我被困住了。

您可以在操作中访问按钮的标题:

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

添加一个字典作为新成员的新成员:

var titleToActionDictionary: [String : String]

现在,在viewDidLoad中,将项目添加到titleToActionDictionary

titleToActionDictionary[newArray[0]] = message // Message is the message you want to show in the alert of the button that has the title newArray[0]

等等。

现在,您的按钮的动作应该看起来像:

@IBAction func myAction(_ sender: UIButton?) {
    let alertMessage = self. titleToActionDictionary[sender.title(for: .normal)]
}

最新更新