我正在嘗試使按鈕顯示警報,具體取決於按鈕的文本。因此,在視圖做負載我有我從陣列拉一些隨機值:在UIview控制器的按鈕動作中使用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 = ""
}
正如你所看到的,valueis集後,該元素從陣列中刪除,以防止它被重用。
然後我給的按鈕這些名字:
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
我不能做什麼,是把這些代碼在按鈕的動作。那是因爲變量ingredient1在viewDidload()中,所以它不能識別變量。我可以把這些變量放在viewDidLoad之外,但是我不能因爲在定義每個隨機值之後從數組中刪除元素,顯然這不可能發生在頂層。
所以我被困住了。
也許答案幫助。但是,*爲什麼*您要刪除「成分」值? (1)似乎對我來說設計不佳。 (2)只需將它們存儲在一個數組*和*中,將它們的索引值與'UIButton'的'tag'值相關聯。這是一個更好的設計,並且不會再佔用更多的「足跡」。這不是2008年(或者對於我們真正的老前輩,1978年),我們需要關心這樣使用的字節數或位數。做對吧! – dfd