2017-09-03 24 views
0

我正在嘗試使按鈕顯示警報,具體取決於按鈕的文本。因此,在視圖做負載我有我從陣列拉一些隨機值:在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

也許答案幫助。但是,*爲什麼*您要刪除「成分」值? (1)似乎對我來說設計不佳。 (2)只需將它們存儲在一個數組*和*中,將它們的索引值與'UIButton'的'tag'值相關聯。這是一個更好的設計,並且不會再佔用更多的「足跡」。這不是2008年(或者對於我們真正的老前輩,1978年),我們需要關心這樣使用的字節數或位數。做對吧! – dfd

回答

0

您可以訪問按鈕的標題在行動像這樣:

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

    ... 
} 
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)] 
} 
相關問題