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

时间:2017-09-03 22:53:14

标签: swift

我试图让按钮显示警告,具体取决于按钮的文字。所以在视图中加载我有一些我从数组中提取的随机值:

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 = ""
}

如您所见,在设置value之后,该元素将从数组中删除,以防止它被重用。

然后我给按钮这些名字:

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)

现在我希望按钮显示特定的消息,具体取决于他们获取的名称。也就是说,如果一个按钮的名字是Oat Milk,点击时,我希望有关燕麦的信息会显示在警报中。

所以我有以下代码:

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

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

所以我被困了。

2 个答案:

答案 0 :(得分:0)

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

#container {
   top: 230px;
   bottom:0; 
   width: 100%; 
   position: fixed; 
   overflow: scroll;
}

答案 1 :(得分:0)

将字典作为新成员添加到您的类中,如下所示:

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)]
}