我有一个称为语言的字符串数组,我想在UIAlertController中创建与数组中的元素一样多的UIAlertAction。我不知道数组会有多大,因为用户可以使用同一UIAlertController中的add选项将语言添加到数组中。
loadLanguages()成功地将userDefaults数据加载到languages数组中,如果有任何现有语言在第一次加载应用程序时已保存为两种入门语言,并且/或者在用户随后使用该应用程序时由用户添加。 >
添加语言选项有效,并存储在userDfeaults(self.saveLanguages)中,并附加到语言数组。
但是,我不确定是否要为languages数组中的每种语言创建UIAlertAction选项。我尝试遍历数组以生成每个菜单项,因为languages数组可以回答应显示多少UIAlertActions,但什么也没有出现。
经过大量搜索之后,我没有发现任何涉及此的内容,但是我敢肯定有一种优雅的方法。
仅供参考:languageChoiceButton声明为:
var languageChoiceButton = UIAlertAction()
@objc func languageMenu(){
loadLanguages()
let chooseLanguageController = UIAlertController(title: "Vocabulary Tutor", message: "Choose a Language", preferredStyle: .actionSheet)
let addLanguage = UIAlertAction(title: "Add Language", style: .default, handler: { (action) -> Void in
let ac = UIAlertController(title: "Add a language", message: nil, preferredStyle: .alert)
ac.addTextField { textField in
textField.placeholder = "New language"
}
let submitAction = UIAlertAction(title: "Add", style: .default) { [unowned self, ac] (action: UIAlertAction!) in
self.newLanguage = ac.textFields?[0].text ?? ""
print("newLanguage: \(self.newLanguage)")
self.languages.append(self.newLanguage)
self.saveLanguages()
self.loadLanguages()
}
ac.addAction(submitAction)
ac.addAction(UIAlertAction(title: "Cancel", style: .cancel))
self.present(ac, animated: true)
})
chooseLanguageController.addAction(addLanguage)
for language in languages {
languageChoiceButton = UIAlertAction(title: language.capitalized, style: .default, handler: { (action) -> Void in
self.chosenLanguage = language
self.title = self.chosenLanguage.capitalized
print("Chosen language is: \(self.chosenLanguage)")
self.loadInitialValues()
chooseLanguageController.addAction(self.languageChoiceButton)
})
}
let cancel = UIAlertAction(title: "Cancel", style: .cancel) {
(action:UIAlertAction!) in
print("Cancel button tapped")
}
chooseLanguageController.addAction(cancel)
self.navigationController!.present(chooseLanguageController, animated: true, completion: nil)
}
答案 0 :(得分:0)
尝试在使用某些语言时创建一个数组,然后循环以将它们中的每一个添加到警报中。
@objc func languageMenu(){
loadLanguages()
let chooseLanguageController = UIAlertController(title: "Vocabulary Tutor", message: "Choose a Language", preferredStyle: .actionSheet)
let i = languages.count - 1
for n in 0...i{
chooseLanguageController.addAction(UIAlertAction(title: arrayLanguage[n].language, style: .default, handler: { (action) in
print(self. languages[n])
}))
}
self.present(chooseLanguageController, animated: true, completion: nil)
}