Я настраиваю UIViewController
с 2 UIButtons
.
Каждая кнопка будет иметь функцию, которая покажет UIAlertController
с несколькими опциями.
Можно ли создать общий метод, чтобы избежать дублирования кода в обеих функциях?
Я уже пытался создать функцию с параметром типа UIAlertController
, но мне не удалось использовать этот параметр.
Здесь я создал пример, чтобы показать вам, что я пытаюсь реорганизовать:
func showFirstMenu(){
let actionSheet = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
let cancel = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)
let optionOne = UIAlertAction(title: "Option 1", style: .default) { action in
self.performSegue(withIdentifier: "optionOne", sender: self)
}
let optionTwo = UIAlertAction(title: "Option 2", style: .default) { action in
self.performSegue(withIdentifier: "optionTwo", sender: self)
}
actionSheet.addAction(optionOne)
actionSheet.addAction(optionTwo)
actionSheet.addAction(cancel)
if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiom.pad ){
actionSheet.popoverPresentationController?.sourceView = self.view
actionSheet.popoverPresentationController?.sourceRect = CGRect(x: self.view.bounds.midX, y: self.view.bounds.midY, width: 0, height: 0)
actionSheet.popoverPresentationController?.permittedArrowDirections = []
self.present(actionSheet, animated: true, completion: nil)
print("Display on iPad")
}
else{
self.present(actionSheet, animated: true, completion: nil)
print("Display on iPhone")
}
}
func showSecondMenu(){
let actionSheet = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
let cancel = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)
let optionThree = UIAlertAction(title: "Option 3", style: .default) { action in
self.performSegue(withIdentifier: "optionThree", sender: self)
}
let optionFour = UIAlertAction(title: "Option 4", style: .default) { action in
self.performSegue(withIdentifier: "optionFour", sender: self)
}
actionSheet.addAction(optionThree)
actionSheet.addAction(optionFour)
actionSheet.addAction(cancel)
if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiom.pad ){
actionSheet.popoverPresentationController?.sourceView = self.view
actionSheet.popoverPresentationController?.sourceRect = CGRect(x: self.view.bounds.midX, y: self.view.bounds.midY, width: 0, height: 0)
actionSheet.popoverPresentationController?.permittedArrowDirections = []
self.present(actionSheet, animated: true, completion: nil)
print("Display on iPad")
}
else{
self.present(actionSheet, animated: true, completion: nil)
print("Display on iPhone")
}
}
Есть ли способ уменьшить это количество кода? Или это единственный способ объявить UIActionSheet
?
Спасибо, если вы прочитали это.