In following code popover on iPad is not centred for second alert (cities) when iPad is rotated. It works fine for first alert (countries) though. I've printed the values and it's same for both alerts. It seems that despite having correct value for coordinates it doesn't present it in centre on device rotation for second alert.
Why it doesn't show in centre for second alert? How to fix it?
class MyVC: UIViewController {
var popoverController:UIPopoverPresentationController?
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransition(to: size, with: coordinator)
self.tableView.reloadData()
if self.popoverController != nil {
popoverController?.sourceView = self.view
print("viewWillTransition():width: x: \(UIScreen.main.bounds.size.width*0.5), y: \(UIScreen.main.bounds.size.height*0.5)")
popoverController?.sourceRect = CGRect(x: UIScreen.main.bounds.size.width*0.5, y: UIScreen.main.bounds.size.height*0.5, width: 0, height: 0)
popoverController?.permittedArrowDirections = []
}
}
#IBAction func countryButtonClicked(_ sender: UIBarButtonItem) {
displayCountries()
}
func displayCountries() {
let alert = UIAlertController(title: "", message: "", preferredStyle: .actionSheet)
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.alignment = .center
let titleAttributedText = NSMutableAttributedString(
string: "Select Country",
attributes: [
NSAttributedString.Key.paragraphStyle: paragraphStyle
]
)
alert.setValue(titleAttributedText, forKey: "attributedMessage")
alert.addAction(UIAlertAction(title: "Cancel", style: UIAlertAction.Style.cancel, handler: countryHandler))
for list in Countries {
alert.addAction(UIAlertAction(title: list, style: .default, handler: countryHandler))
}
// For iPad
if let poController = alert.popoverPresentationController {
popoverController = poController
popoverController?.sourceView = self.view
print("displayCountries():width: x: \(UIScreen.main.bounds.size.width*0.5), y: \(UIScreen.main.bounds.size.height*0.5)")
popoverController?.sourceRect = CGRect(x: UIScreen.main.bounds.size.width*0.5, y: UIScreen.main.bounds.size.height*0.5, width: 0, height: 0)
popoverController?.permittedArrowDirections = []
}
alert.view.addSubview(UIView())
present(alert, animated: false, completion: nil)
}
#IBAction func cityButtonClicked(_ sender: Any) {
showCities()
}
func showCities(){
let alert = UIAlertController(title: "Select City", message: nil, preferredStyle: .actionSheet)
for listItem in Cities {
alert.addAction(UIAlertAction(title: listItem.title, style: .default, handler: cityHandler))
}
alert.addAction(UIAlertAction(title: "Cancel", style: UIAlertAction.Style.cancel, handler: cityHandler))
if let popoverController = alert.popoverPresentationController {
popoverController.sourceView = self.view
print("showCities():width: x: \(UIScreen.main.bounds.size.width*0.5), y: \(UIScreen.main.bounds.size.height*0.5)")
popoverController.sourceRect = CGRect(x: UIScreen.main.bounds.size.width*0.5, y: UIScreen.main.bounds.size.height*0.5, width: 0, height: 0)
popoverController.permittedArrowDirections = []
}
alert.view.addSubview(UIView())
present(alert, animated: false, completion: nil)
}
}
popoverController must be also assigned in second alert:
if let popoverController = alert.popoverPresentationController {
self.popoverController = popoverController
...
Related
I am trying to get all the elements (UItextfields) that I have in defined in myScrollView in class AddViewController to another FormViewController where I have just an empty getFormView scrollview where I want to get all the elements of myScrollView to be appear, whether in a form of copy or getting that same.
I am adding subview of myScrollView to getFormView but this gives me error
unexpectedly found nil while unwrapping an optional
I am creating textfields by getting an input, like if set input to 7 the seven textfields will be generated in form and by clicking on creating I want these testfields should be in formViewController's uiscrollview that is getformview
FormViewController
import UIKit
class FormViewController: UIViewController {
#IBOutlet weak var menu: UIBarButtonItem!
#IBOutlet weak var getFormView: UIScrollView!
override func viewDidLoad() {
super.viewDidLoad()
menu.target = revealViewController()
menu.action = #selector(SWRevealViewController.revealToggle(_:))
self.view.addGestureRecognizer(self.revealViewController().panGestureRecognizer())
getFormView.alwaysBounceVertical = true
getFormView.scrollsToTop = true
getFormView.isScrollEnabled = true
getFormView.contentSize = CGSize(width: 343, height: 1500)
print("formViewController")
let mainStoryBoard: UIStoryboard = UIStoryboard(name: "Main", bundle : nil)
let desController = mainStoryBoard.instantiateViewController(withIdentifier: "AddViewController") as! AddViewController
self.view.addSubview(self.getFormView)
self.getFormView.addSubview(desController.myScrollView)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
AddViewController Image of my myScrollView
enter image description here
FormViewController image of getFormView
enter image description here
AddViewController
import UIKit
class AddViewController: UIViewController {
var templateName : String?
var templateDesc : String?
var noButtons : Int?
var noTextFields : Int?
var noLabels : Int?
var xValue = 20, yValue = 100
var tagNo = 0
var textObjects : Array<Any>?
var incrementerText : Int?
var xButton = 15 , yButton = 90
var tagButton = 10
var buttonObject : Array<Any>?
var buttonIncreament : Int?
var xLabel = 10 , yLabel = 80
var tagLabel = 15
var labelObject : Array<Any>?
var labelIncreament : Int?
#IBOutlet weak var menu: UIBarButtonItem!
#IBOutlet weak var myScrollView: UIScrollView!
#IBOutlet weak var reset: UIButton!
#IBAction func reset(_ sender: Any) {
let mainStoryBoard: UIStoryboard = UIStoryboard(name: "Main", bundle : nil)
let desController = mainStoryBoard.instantiateViewController(withIdentifier: "AddViewController") as! AddViewController
let newFrontViewController = UINavigationController.init(rootViewController:desController)
revealViewController().pushFrontViewController(newFrontViewController, animated: true)
}
#IBOutlet weak var createForms: UIButton!
#IBAction func createForms(_ sender: Any) {
let mainStoryBoard: UIStoryboard = UIStoryboard(name: "Main", bundle : nil)
let desController = mainStoryBoard.instantiateViewController(withIdentifier: "FormViewController") as! FormViewController
// desController.getFormView.addSubview(myScrollView)
let newFrontViewController = UINavigationController.init(rootViewController:desController)
revealViewController().pushFrontViewController(newFrontViewController, animated: true)
}
#IBAction func addForm(_ sender: Any) {
let alertController = UIAlertController(title: "Create Template", message: "", preferredStyle: .alert)
alertController.extendedLayoutIncludesOpaqueBars = true
alertController.addTextField { (textField: UITextField) in
// textField.keyboardAppearance = .dark
textField.keyboardType = .default
textField.autocorrectionType = .default
textField.placeholder = "Title"
textField.clearButtonMode = .whileEditing
}
alertController.addTextField { (textField: UITextField) in
//textField.keyboardAppearance = .dark
textField.keyboardType = .default
textField.autocorrectionType = .default
textField.placeholder = "Description"
textField.clearButtonMode = .whileEditing
}
let okAction = UIAlertAction(title: "Continue", style: UIAlertActionStyle.default) {
UIAlertAction in
print("Ok action")
let templateText = alertController.textFields![0]
let descriptionText = alertController.textFields![1]
self.templateName = templateText.text!
self.templateDesc = descriptionText.text!
if self.templateName?.isEmpty == false && self.templateDesc?.isEmpty == false {
print("Template: \(templateText.text!)\nDescription: \(descriptionText.text!)")
print("\(String(describing: self.templateName!)), \(String(describing: self.templateDesc!))")
self.dismiss(animated: true, completion: nil)
self.drawPop()
}
else {
self.okAlert()
}
}
let cancelAction = UIAlertAction(title: "Cancel", style: .destructive) {
UIAlertAction in
self.dismiss(animated: true, completion: nil)
NSLog("Cancel Pressed")
}
//alertController.addAction(alertActionOkay)
// Add the actions
alertController.addAction(cancelAction)
alertController.addAction(okAction)
// alertController.willChangeValue(forKey: "Continue")
// Present the controller
self.present(alertController, animated: true, completion: nil)
}
func drawPop() {
let alertController = UIAlertController(title: "\(self.templateName!)", message: "\(self.templateDesc!)", preferredStyle: .alert)
//attributing textfields labels
alertController.addTextField { (textField: UITextField) in
//textField.keyboardAppearance = .dark
textField.keyboardType = UIKeyboardType.numberPad
// textField.keyboardType = .default
textField.placeholder = "TextFileds"
textField.clearButtonMode = .whileEditing
}
alertController.addTextField { (textField: UITextField) in
// textField.keyboardAppearance = .dark
textField.keyboardType = UIKeyboardType.numberPad
textField.autocorrectionType = .default
textField.placeholder = "Buttons"
textField.clearButtonMode = .whileEditing
}
alertController.addTextField { (textField: UITextField) in
// textField.keyboardAppearance = .dark
textField.keyboardType = UIKeyboardType.numberPad
textField.autocorrectionType = .default
textField.placeholder = "Labels"
textField.clearButtonMode = .whileEditing
}
// Create the actions
let okAction = UIAlertAction(title: "Done", style: UIAlertActionStyle.default) {
UIAlertAction in
NSLog("OK Pressed")
let notextFieldText = alertController.textFields![0]
let noButtonText = alertController.textFields![1]
let noLabelText = alertController.textFields![2]
self.noTextFields = Int(notextFieldText.text!)
self.noButtons = Int(noButtonText.text!)
self.noLabels = Int(noButtonText.text!)
print("Template: \(notextFieldText.text!)\nDescription: \(noButtonText.text!)")
print("\(noLabelText.text!)")
print("\(String(describing: self.noTextFields!)), \(String(describing: self.noButtons!)) , \(String(describing: self.noLabels!))")
self.createForms.isHidden = false
self.myScrollView.isHidden = false
self.reset.isHidden = false
self.incrementerText = 20
if self.noTextFields! > 0 {
for _ in 0..<self.noTextFields! {
print ("hello")
let sampleTextField = UITextField(frame: CGRect(x: self.xValue, y: self.yValue, width: 300, height: 40))
sampleTextField.placeholder = "Enter text here"
sampleTextField.font = UIFont.systemFont(ofSize: 15)
sampleTextField.borderStyle = UITextBorderStyle.roundedRect
sampleTextField.autocorrectionType = UITextAutocorrectionType.no
sampleTextField.keyboardType = UIKeyboardType.default
sampleTextField.returnKeyType = UIReturnKeyType.done
sampleTextField.clearButtonMode = UITextFieldViewMode.whileEditing;
sampleTextField.contentVerticalAlignment = UIControlContentVerticalAlignment.center
sampleTextField.delegate = self as? UITextFieldDelegate
sampleTextField.tag = self.tagNo
// self.view.addSubview(sampleTextField)
//trying to print at container view
self.view.addSubview(self.myScrollView)
self.myScrollView.addSubview(sampleTextField)
let frametext = sampleTextField.frame.size.height
self.textObjects?.append(sampleTextField)
self.yValue = self.yValue + Int(frametext) + 20
self.xValue = 20
}
}
else {
print("no text field found")
}
self.buttonIncreament = 20
if self.noButtons! > 0 {
for _ in 0..<self.noButtons! {
print ("Buttons")
let sampleButton = UIButton(frame: CGRect(x: self.xButton, y: self.yButton, width: 150, height: 25))
sampleButton.contentVerticalAlignment = UIControlContentVerticalAlignment.center
sampleButton.tag = self.tagNo
// self.view.addSubview(sampleButton)
let frametext = sampleButton.frame.size.height
self.view.addSubview(self.myScrollView)
self.myScrollView.addSubview(sampleButton)
self.buttonObject?.append(sampleButton)
self.yButton = self.yButton + Int(frametext) + 20
self.xButton = 20
}
}
else {
print("no button found")
}
self.labelIncreament = 20
if self.noLabels! > 0 {
for _ in 0..<self.noLabels! {
print ("Labels")
let sampleLabel = UILabel(frame: CGRect(x: self.xLabel, y: self.yLabel, width: 150, height: 25))
// sampleLabel.contentVerticalAlignment = UIControlContentVerticalAlignment.center
sampleLabel.tag = self.tagNo
// self.view.addSubview(sampleButton)
let frameLabel = sampleLabel.frame.size.height
self.view.addSubview(self.myScrollView)
self.myScrollView.addSubview(sampleLabel)
self.labelObject?.append(sampleLabel)
self.yLabel = self.yLabel + Int(frameLabel) + 20
self.xLabel = 20
}
}
else {
print("no button found")
}
self.dismiss(animated: true, completion: nil)
}
let cancelAction = UIAlertAction(title: "Cancel", style: .destructive) {
UIAlertAction in
self.dismiss(animated: true, completion: nil)
NSLog("Cancel Pressed")
}
//alertController.addAction(alertActionOkay)
// Add the actions
alertController.addAction(cancelAction)
alertController.addAction(okAction)
// Present the controller
self.present(alertController, animated: true, completion: nil)
}
func createForm() {
let sampleTextField = UITextField(frame: CGRect(x: 20, y: 100, width: 300, height: 40))
sampleTextField.placeholder = "Enter text here"
sampleTextField.font = UIFont.systemFont(ofSize: 15)
sampleTextField.borderStyle = UITextBorderStyle.roundedRect
sampleTextField.autocorrectionType = UITextAutocorrectionType.no
sampleTextField.keyboardType = UIKeyboardType.default
sampleTextField.returnKeyType = UIReturnKeyType.done
sampleTextField.clearButtonMode = UITextFieldViewMode.whileEditing;
sampleTextField.contentVerticalAlignment = UIControlContentVerticalAlignment.center
sampleTextField.delegate = self as? UITextFieldDelegate
self.view.addSubview(sampleTextField)
}
func okAlert() {
let alertController = UIAlertController(title: "Oops!", message: "Enter required data", preferredStyle: .alert)
let defaultAction = UIAlertAction(title: "OK", style: .default, handler: nil)
alertController.addAction(defaultAction)
present(alertController, animated: true, completion: nil)
}
/*
let scrollmyView : UIScrollView = {
let scrollView = UIScrollView()
scrollView.alwaysBounceVertical = true
scrollView.scrollsToTop = true
// myScrollView.alwaysBounceHorizontal = true
scrollView.isScrollEnabled = true
scrollView.contentSize = CGSize(width: 200, height: 1500)
return scrollView
}()
*/
override func viewDidLoad() {
super.viewDidLoad()
menu.target = revealViewController()
menu.action = #selector(SWRevealViewController.revealToggle(_:))
self.view.addGestureRecognizer(self.revealViewController().panGestureRecognizer())
myScrollView.alwaysBounceVertical = true
myScrollView.scrollsToTop = true
// myScrollView.alwaysBounceHorizontal = true
myScrollView.isScrollEnabled = true
myScrollView.contentSize = CGSize(width: 343, height: 1500)
// scroller.contentSize = CGSize(width: yourWidth, height: yourHeight)
createForms.isHidden = true
myScrollView.isHidden = true
reset.isHidden = true
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
Error
Full screen error
Why you are using scrollview if you have same type of elements. Best way is to use table view. We use scrollview if the elements in most of the rows are different. Once you use table view you don't have to copy anything.
Best approach for your problem:
If you have same type of view controller then you can use one view controller as AddViewController and FormViewController.
Create the same UITextFields in your FormViewController.
and when a user fills the form in AddViewController , update the textfields of your FormViewController with the text of AddViewController's text field
content.view.frame = CGRect(x: -UIScreen.main.bounds.size.width, y: 0, width: UIScreen.main.bounds.size.width, height: view.frame.size.height)
getFormView = content.scrollView
view.addSubview(content.scollView)
content.didMove(toParentViewController: self)
Here content is the view controller that you want to add in you case it is instance of AddViewController
i have an AlertController with UITextView.
when UITexView become first responder the alter doesn't move up with the keyboard.
this is my code:
#IBAction func showAlert(sender: AnyObject) {
let alertController = UIAlertController(title: "Hello, I'm alert! \n\n\n\n\n\n\n", message: "", preferredStyle: .alert)
let rect = CGRect(x: 15, y: 15, width: 240, height: 150)//CGRectMake(15, 50, 240, 150.0)
let textView = UITextView(frame: rect)
textView.font = UIFont(name: "Helvetica", size: 15)
textView.textColor = UIColor.lightGray
textView.backgroundColor = UIColor.white
textView.layer.borderColor = UIColor.lightGray.cgColor
textView.layer.borderWidth = 1.0
textView.text = "Enter message here"
textView.delegate = self
alertController.view.addSubview(textView)
let cancel = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)
let action = UIAlertAction(title: "Ok", style: .default, handler: { action in
let msg = (textView.textColor == UIColor.lightGray) ? "" : textView.text
print(msg!)
})
alertController.addAction(cancel)
alertController.addAction(action)
self.present(alertController, animated: true, completion: {
textView.becomeFirstResponder()
})
}
and this is my result:
there is a solution?
thanks in advance
just addTextField and then remove it
alert.addTextField { field in
field.translatesAutoresizingMaskIntoConstraints = false
field.heightAnchor.constraint(equalToConstant: 0).isActive = true
}
let inCntrlr = alert.childViewControllers[0].view!
inCntrlr.removeFromSuperview()
and then you could add your own views. here is a
result
After presenting alert controller. Open keyboard for TextView and move alert controller up.
I hope this will suite for you.
self.present(alertController, animated: true, completion: {
textView.becomeFirstResponder()
UIView.animate(withDuration: 0.5, animations: {
alertController.view.frame.origin.y = 100
})
})
UIAlertController by default will slide up when they keyboard is shown. The problem here is that you have added a subview to the alert controller. From the UIAlertController docs:
The UIAlertController class is intended to be used as-is and does not
support subclassing. The view hierarchy for this class is private and
must not be modified.
Adding your own subview to the alert goes against what the docs say and is likely what is causing your problem. If you need an alert with a text view in it, your best bet is to create your own view and manage it yourself.
I created this drop-in replacement, also customizable for any special needs of course. It's pretty simple and 'just works'!
https://gist.github.com/unixb0y/42a1ae0fb707bdb5e1e484bafd33d44a
It is a subclass of UIAlertController with a UITextView inside.
When it is initialized, it observes keyboard changes and adjusts its view.frame.origin.y accordingly.
var keyboardHeight: CGFloat = 100 {
didSet {
let height = UIScreen.main.bounds.height
let menu = self.view.frame.height
let keyb = self.keyboardHeight
self.view.frame.origin.y = height-menu-keyb-20
}
}
...
...
...
#objc func keyboardChange(sender: Notification) {
guard let userInfo = sender.userInfo else { return }
let endFrame = userInfo[UIResponder.keyboardFrameEndUserInfoKey] as? CGRect
keyboardHeight = endFrame?.height ?? 100
}
It's like. You open keyboard and change alert position.
var alertController = UIAlertController(title: nil, message: nil, preferredStyle: UIAlertController.Style.alert)
var alertControllerPositon:CGFloat = 0
override func viewDidLoad() {
super.viewDidLoad()
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name: UIResponder.keyboardWillShowNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide), name: UIResponder.keyboardWillHideNotification, object: nil)
}
#IBAction func showAlert(sender: AnyObject) {
let alertController = UIAlertController(title: "Hello, I'm alert! \n\n\n\n\n\n\n", message: "", preferredStyle: .alert)
let rect = CGRect(x: 15, y: 15, width: 240, height: 150)//CGRectMake(15, 50, 240, 150.0)
let textView = UITextView(frame: rect)
textView.font = UIFont(name: "Helvetica", size: 15)
textView.textColor = UIColor.lightGray
textView.backgroundColor = UIColor.white
textView.layer.borderColor = UIColor.lightGray.cgColor
textView.layer.borderWidth = 1.0
textView.text = "Enter message here"
textView.delegate = self
alertController.view.addSubview(textView)
let cancel = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)
let action = UIAlertAction(title: "Ok", style: .default, handler: { action in
let msg = (textView.textColor == UIColor.lightGray) ? "" : textView.text
print(msg!)
})
alertController.addAction(cancel)
alertController.addAction(action)
self.present(alertController, animated: true, completion: {
textView.becomeFirstResponder()
})
alertControllerPositon = alertController.view.frame.origin.y
}
#objc func keyboardWillShow(notification: NSNotification) {
if let keyboardSize = (notification.userInfo?[UIResponder.keyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
alertControllerPositon = alertController.view.frame.origin.y
let result = self.view.frame.height - (alertController.view.frame.height + alertController.view.frame.origin.y) - 20
self.alertController.view.frame.origin.y -= (keyboardSize.height - result)
}
}
#objc func keyboardWillHide(notification: NSNotification) {
if self.alertController.view.frame.origin.y != alertControllerPositon {
self.alertController.view.frame.origin.y = alertControllerPositon
}
}
I want to add a UIStepper to my alerView but the stepper is not showing here is my code
var alert = UIAlertView(title: "Hello works", message: "\n\n", delegate: nil, cancelButtonTitle: "OK", otherButtonTitles: "")
var stepper = UIStepper()
stepper.frame = CGRect(x: CGFloat(12.0), y: CGFloat(5.0), width: CGFloat(100), height: CGFloat(10))
alert.addSubview(stepper)
alert.show()
UIAlertView is deprecated. You should use UIAlertController instead. Here is an answer that explains how you can implement what you want using a UIAlertController:
UIAlertController - add custom views to actionsheet
// Below is code for implementing UIAlertView Using UIAlertController in swift and add your custom views on it .
let logoutAlert = UIAlertController(title: "Alert", message: "DemoAlert", preferredStyle: UIAlertControllerStyle.alert)
logoutAlert.addAction(UIAlertAction(title: "cancel", style: .default, handler: nil))
logoutAlert.addAction(UIAlertAction(title: "Ok", style: .default, handler: { (action: UIAlertAction!) in
// Write your code here
}))
var stepper = UIStepper()
stepper.frame = CGRect(x: CGFloat(12.0), y: CGFloat(5.0), width: CGFloat(100), height: CGFloat(10))
// You can add any view on UIAlert controller using below code:
logoutAlert.popoverPresentationController?.sourceRect = stepper.frame
logoutAlert.popoverPresentationController?.sourceView = stepper
self.present(logoutAlert, animated: true, completion: nil)
I am very new to swift coding so I want to know that is there any way to show tableview in alertcontroller using swift.
var alrController = UIAlertController(title: "\n\n\n\n\n\n", message: nil, preferredStyle: UIAlertControllerStyle.ActionSheet)
let margin:CGFloat = 8.0
let rect = CGRectMake(margin, margin, alrController.view.bounds.size.width - margin * 4.0, 100.0)
var tableView = UITableView(frame: rect)
tableView.delegate = self
tableView.dataSource = self
tableView.backgroundColor = UIColor.greenColor()
alrController.view.addSubview(tableView)
let somethingAction = UIAlertAction(title: "Something", style: UIAlertActionStyle.Default, handler: {(alert: UIAlertAction!) in println("something")})
let cancelAction = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel, handler: {(alert: UIAlertAction!) in println("cancel")})
alrController.addAction(somethingAction)
alrController.addAction(cancelAction)
self.presentViewController(alrController, animated: true, completion:{})
private var alertController = UIAlertController()
private var tblView = UITableView()
private func setupCitySelectionAlert() {
let alertVC = UIViewController.init()
let rect = CGRect(x: 0.0, y: 0.0, width: 300.0, height: 300.0)
alertVC.preferredContentSize = rect.size
tblView = UITableView(frame: rect)
tblView.delegate = self;
tblView.dataSource = self;
tblView.tableFooterView = UIView(frame: .zero)
tblView.separatorStyle = .singleLine
alertVC.view.addSubview(tblView)
alertVC.view.bringSubviewToFront(tblView)
alertVC.view.isUserInteractionEnabled = true
tblView.isUserInteractionEnabled = true
tblView.allowsSelection = true
self.alertController = UIAlertController(title: "Title", message: nil, preferredStyle: .alert)
alertController.setValue(alertVC, forKey: "contentViewController")
let cancelAction = UIAlertAction(title: "Cancel", style: .default, handler: nil)
alertController.addAction(cancelAction)
self.present(alertController, animated: true, completion: nil)
}
This question already has an answer here:
Picking two different images in the same view controller using imagePickerController in Swift
(1 answer)
Closed 7 years ago.
We have the following view:
All code is running well but when I finally select a picture , the photo is placed just in one ImageView. It should works like this:
We click each button below the UIImageView and it puts the selected picture in his ImageView.
My problem now is that all buttons are placing the photo in the first UIImageView.
How to place 4 different photos?
class selectorDeFotosViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate, UITextViewDelegate {
//Outlets
#IBOutlet weak var fotoUno: UIImageView!
#IBOutlet weak var fotoDos: UIImageView!
#IBOutlet weak var fotoTres: UIImageView!
#IBOutlet weak var fotoCuatro: UIImageView!
override func viewDidLoad() {
}
//Actions
#IBAction func CamaraUno(sender: AnyObject) {
let alertPictureFrom = UIAlertController(title: "De dónde sacar la foto?", message: "", preferredStyle: UIAlertControllerStyle.ActionSheet)
presentViewController(alertPictureFrom, animated: true, completion: nil)
alertPictureFrom.popoverPresentationController?.sourceRect = CGRect(x: 350.0, y: 458.0, width: 1.0, height: 1.0)
alertPictureFrom.popoverPresentationController?.sourceView = self.view
alertPictureFrom.addAction(UIAlertAction(title: "Cámara", style: .Default, handler: {action in
let picker = UIImagePickerController()
picker.sourceType = .Camera
picker.delegate = self
picker.allowsEditing = true
self.presentViewController(picker, animated: true, completion: nil)
}))
alertPictureFrom.addAction(UIAlertAction(title: "Galería", style: .Default, handler: {action in
let picker = UIImagePickerController()
picker.sourceType = .PhotoLibrary
picker.delegate = self
picker.allowsEditing = true
self.presentViewController(picker, animated: true, completion: nil)
}))
}
#IBAction func camaraDos(sender: AnyObject) {
let alertPictureFrom = UIAlertController(title: "De dónde sacar la foto?", message: "", preferredStyle: UIAlertControllerStyle.ActionSheet)
presentViewController(alertPictureFrom, animated: true, completion: nil)
alertPictureFrom.popoverPresentationController?.sourceRect = CGRect(x: 350.0, y: 458.0, width: 1.0, height: 1.0)
alertPictureFrom.popoverPresentationController?.sourceView = self.view
alertPictureFrom.addAction(UIAlertAction(title: "Cámara", style: .Default, handler: {action in
let picker = UIImagePickerController()
picker.sourceType = .Camera
picker.delegate = self
picker.allowsEditing = true
self.presentViewController(picker, animated: true, completion: nil)
}))
alertPictureFrom.addAction(UIAlertAction(title: "Galería", style: .Default, handler: {action in
let picker = UIImagePickerController()
picker.sourceType = .PhotoLibrary
picker.delegate = self
picker.allowsEditing = true
self.presentViewController(picker, animated: true, completion: nil)
}))
}
#IBAction func camaraTres(sender: AnyObject) {
let alertPictureFrom = UIAlertController(title: "De dónde sacar la foto?", message: "", preferredStyle: UIAlertControllerStyle.ActionSheet)
presentViewController(alertPictureFrom, animated: true, completion: nil)
alertPictureFrom.popoverPresentationController?.sourceRect = CGRect(x: 350.0, y: 458.0, width: 1.0, height: 1.0)
alertPictureFrom.popoverPresentationController?.sourceView = self.view
alertPictureFrom.addAction(UIAlertAction(title: "Cámara", style: .Default, handler: {action in
let picker = UIImagePickerController()
picker.sourceType = .Camera
picker.delegate = self
picker.allowsEditing = true
self.presentViewController(picker, animated: true, completion: nil)
}))
alertPictureFrom.addAction(UIAlertAction(title: "Galería", style: .Default, handler: {action in
let picker = UIImagePickerController()
picker.sourceType = .PhotoLibrary
picker.delegate = self
picker.allowsEditing = true
self.presentViewController(picker, animated: true, completion: nil)
}))
}
#IBAction func camaraCuatro(sender: AnyObject) {
let alertPictureFrom = UIAlertController(title: "De dónde sacar la foto?", message: "", preferredStyle: UIAlertControllerStyle.ActionSheet)
presentViewController(alertPictureFrom, animated: true, completion: nil)
alertPictureFrom.popoverPresentationController?.sourceRect = CGRect(x: 350.0, y: 458.0, width: 1.0, height: 1.0)
alertPictureFrom.popoverPresentationController?.sourceView = self.view
alertPictureFrom.addAction(UIAlertAction(title: "Cámara", style: .Default, handler: {action in
let picker = UIImagePickerController()
picker.sourceType = .Camera
picker.delegate = self
picker.allowsEditing = true
self.presentViewController(picker, animated: true, completion: nil)
}))
alertPictureFrom.addAction(UIAlertAction(title: "Galería", style: .Default, handler: {action in
let picker = UIImagePickerController()
picker.sourceType = .PhotoLibrary
picker.delegate = self
picker.allowsEditing = true
self.presentViewController(picker, animated: true, completion: nil)
}))
}
func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
fotoUno.image = image
picker.dismissViewControllerAnimated(true, completion: nil)
}
There are many ways to achieve this.
You press button1, and set a BOOL value buttonOne to YES, and you present the picker, you select the image, and to display the image, you simply check is button is selected or not in the method didFinishPickingImage,so:
if(buttonOne)
{
//set the image view 1 image
}
You do the same for all the four image views:
if(buttonOne)
{
//set the image view 1 image
}
if(buttonTwo)
{
//set the image view 2 image
} if(buttonThree)
{
//set the image view 3 image
} if(buttonFour)
{
//set the image view 4 image
}
Make sure you set the other 3 bool values to NO, when you set one value to YES.