I want to be able to change the title displayed in the navigationBar. I have the alertController setup and it appears fine, however after inputting the newTitle text, the current title disappears but the new title doesn't appear. I have tried reloading data in the viewDidLoad, viewWillAppear, as well as in the button press event itself (as shown in code). Any input is appreciated.
#IBAction func changeTitleBarButtonPressed(_ sender: UIBarButtonItem) {
let titleChange = UIAlertController(
title: "Change Title",
message: "Please input text to change the title",
preferredStyle: .alert)
titleChange.addTextField { (textField) in
textField.placeholder = "Input new title"
}
titleChange.addAction(UIAlertAction(
title: "Cancel",
style: .cancel,
handler: { (cancelAction) in
titleChange.dismiss(animated: true)
}))
titleChange.addAction(UIAlertAction(
title: "Change Title",
style: .default,
handler: { (changeAction) in
let newTitle = self.textField?.text
titleChange.dismiss(animated: true)
self.navigationItem.title = newTitle
self.imagesTableView.reloadData()
}))
self.present(titleChange, animated: true)
}
The only problem is you read the text value from unrelated textField (And its probably nil or empty). You may want to use the first textField of the alert instead of self.textField?.text:
titleChange.addAction(UIAlertAction(
title: "Change Title",
style: .default,
handler: { (changeAction) in
let newTitle = titleChange.textFields![0].text // instead of `self.textField?.text`
titleChange.dismiss(animated: true) // this line is not required. You can get rid of it freely.
self.navigationItem.title = newTitle
}))
Make sure you are no setting the navigationItem.title elsewhere (like viewWillAppear or etc.)
Related
I am having problems in adding a second text field to my completion block.
Can someone please show me on how to add one more textfield please.
I am trying to add a self.newFirstNameInput = // this is the part that I do not understand?
func insertNewObject(sender: AnyObject) {
let newNameAlert = UIAlertController(title: "Add New User", message: "What's the user's name?", preferredStyle: UIAlertControllerStyle.Alert)
newNameAlert.addTextFieldWithConfigurationHandler { (alertTextField) -> Void in
self.newLastNameInput = alertTextField
}
newNameAlert.view.setNeedsLayout()
newNameAlert.addAction(UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Default, handler: nil))
newNameAlert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: addNewUser))
presentViewController(newNameAlert, animated: true, completion: nil)
}
var txtField1: UITextField!
var txtField2: UITextField!
override func viewDidLoad()
{
let alert = UIAlertController(title: "Enter Input", message: "", preferredStyle: UIAlertControllerStyle.Alert)
alert.addTextFieldWithConfigurationHandler(addTextField1)
alert.addTextFieldWithConfigurationHandler(addTextField2)
alert.addAction(UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel, handler: { (UIAlertAction)in
print("Cancel")
}))
alert.addAction(UIAlertAction(title: "Done", style: UIAlertActionStyle.Default, handler:{ (UIAlertAction)in
print("Done")
print("First Name : \(self.txtField1.text!)")
print("Last Name : \(self.txtField2.text!)")
}))
self.presentViewController(alert, animated: true, completion: nil)
}
func addTextField1(textField: UITextField!)
{
textField.placeholder = "Enter first name"
txtField1 = textField
}
func addTextField2(textField: UITextField!)
{
textField.placeholder = "Enter last name"
txtField2 = textField
}
i hope my answer help you...
Hello I am making a ViewController with a PickerView that has age restrictions. I made it with the alert and age restrictions but I need it to deny access to next ViewController if the user isn't old enough.
Made my code like this, I guess its in the Else true I need some more code, but I'm not sure tho. I hope a kind soul can help me :)
#IBAction func verificerKnap(sender: AnyObject) {
// Creating the age restriction for the datepicker
let dateOfBirth = datoPicker.date
let today = NSDate()
let gregorian = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)!
let age = gregorian.components([.Year], fromDate: dateOfBirth, toDate: today, options: [])
if age.year < 18 {
// Alert controller som sender en advarsel hvis personen er under 18år
let alertController = UIAlertController(title: "Age restriction", message:
"This app requires an age of 18+", preferredStyle: UIAlertControllerStyle.Alert)
alertController.addAction(UIAlertAction(title: "Okay", style: UIAlertActionStyle.Default,handler: nil))
self.presentViewController(alertController, animated: true, completion: nil)
} else {
true
You can present an UIAlertController which asks if you are 18 years or older. Than link 2 buttons "Ok" and "Cancel" and add delegates for those:
let alertController = UIAlertController(title: "Default Style", message: "Are you 18 years or older?", preferredStyle: .Alert)
let cancelAction = UIAlertAction(title: "Cancel", style: .Cancel) {
(action) in
print("User is not yet >18")
}
alertController.addAction(cancelAction)
let OKAction = UIAlertAction(title: "OK", style: .Default) {
(action) in
dispatch_async(dispatch_get_main_queue(), {
self.presentViewController(desired_view_controller, animated: true, completion: nil)
})
}
alertController.addAction(OKAction)
self.presentViewController(alertController, animated: true) {
// ...
}
based on: http://nshipster.com/uialertcontroller/
I want to load an alert when internet connection is not available. The function for checking internet connection is ready but I cannot load the alert. So I just put the alert code in viewDidLoad without any conditions etc. and got this error:
Warning: Attempt to present UIAlertController: 0x12752d400 on x.ViewController: 0x127646f00 whose view is not in the window hierarchy!
Code:
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
// Delegates
verificationCode.delegate = self
let alert = UIAlertController(title: "Oops!", message:"This feature isn't available right now", preferredStyle: .Alert)
let action = UIAlertAction(title: "OK", style: .Default) { _ in }
alert.addAction(action)
self.presentViewController(alert, animated: true) {}
if (!Util.isConnectedToNetwork()) {
self.isConnected = false
}
}
Could you tell me how to fix it?
The error tells you what has gone wrong.
You are trying to present a view controller in viewDidLoad except the view, although loaded, is not in any hierarchy. Try putting the code in the viewDidAppear method, which is called after the view appears on screen, and is in a view hierarchy.
Swift 4 Update
I think this could help you for your problem :
override func viewDidLoad() {
super.viewDidLoad()
verificationCode.delegate = self
let alert = UIAlertController(title: "Oops!", message:"This feature isn't available right now", preferredStyle: .alert)
let delete = UIAlertAction(title: "OK", style: .default) { (_) in }
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel) { (_) in }
alert.addAction(cancelAction)
alert.addAction(delete)
alert.popoverPresentationController?.sourceView = sender as UIView
UIApplication.shared.keyWindow?.rootViewController?.present(alert, animated: true, completion: nil)
if (!Util.isConnectedToNetwork()) {
self.isConnected = false
}
}
Move the code to viewDidAppear from viewDidLoad
override func viewDidAppear(animated: Bool) {
// Delegates
verificationCode.delegate = self
let alert = UIAlertController(title: "Oops!", message:"This feature isn't available right now", preferredStyle: .Alert)
let action = UIAlertAction(title: "OK", style: .Default) { _ in }
alert.addAction(action)
self.presentViewController(alert, animated: true) {}
if (!Util.isConnectedToNetwork()) {
self.isConnected = false
}
}
I'm working in these lines trying to show an "Error" message if the user forgot to fill the username label or choose an option from the PickerView ("-- Choose an option please --"), but, when I run this, it takes also the other options from the picker view as an error.
If the user choose A,B,C,D it's okay. I just want to define the first one ("-- Choose an option please --") as an error, but it doesn't works.
class ViewController: UIViewController, UIPickerViewDataSource, UIPickerViewDelegate {
let userRole:[String] = ["-- Choose an option please --", "A", "B", "C", "D"]
var selectedOption:String?
#IBOutlet weak var usernameLabel: UITextField!
#IBOutlet weak var pickerRoleLabel: UIPickerView!
#IBAction func continueButton(sender: AnyObject) {
if usernameLabel.text == "" || userRole[0] == "-- Choose an option please --" {
let alert = UIAlertController(title: "Error in form", message: "Please fill the information", preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "Okay", style: .Default, handler: { (action) -> Void in
self.dismissViewControllerAnimated(true, completion: nil)
}))
self.presentViewController(alert, animated: true, completion: nil)
}
}
How can I improve this?
Thanks in advance!
You could always ensure your "-- Choose an option please --" string as first item. So you can just test if the value of the desired component with UIPickerView´s selectedRowInComponent method is bigger than "0".
If "0" is returned from this method, means your first position is selected, but if you receive "-1", no value was selected in your picker. Any value bigger than "0" you can considerate as a valid value.
selectedRowInComponent(_ component: Int)
#IBAction func continueButton(sender: AnyObject) {
//If you
if usernameLabel.text == "" || myPickerView.selectedRowInComponent(0) < 1 {
let alert = UIAlertController(title: "Error in form", message: "Please fill the information", preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "Okay", style: .Default, handler: { (action) -> Void in
self.dismissViewControllerAnimated(true, completion: nil)
}))
self.presentViewController(alert, animated: true, completion: nil)
}
}
I want the user to type up the text in the pop up dialog, but I want the program to wait until the user finished writing the text in the pop up dialog
Use UIAlertController:
let alertController = UIAlertController(title: "title", message: nil, preferredStyle: .Alert)
alertController.addTextFieldWithConfigurationHandler { (textField) -> Void in }
alertController.addAction(UIAlertAction(title: "cancel", style: UIAlertActionStyle.Cancel, handler: nil))
logInAlertController.addAction(UIAlertAction(title: "go", style: UIAlertActionStyle.Default, handler: { (action) -> Void in }
Swift 4
It sounds like you are doing your completion handling when presenting the controller instead of when the user selects an alert action.
You'll want to try something like this:
import UIKit
class MyViewController: UIViewController
{
var someStringVariable:String = ""
func presentAnAlert()
{
let alert = UIAlertController(
title: "Title",
message: "Message",
preferredStyle: .actionSheet //choose which style you prefer
)
alert.addTextField()
{ (textField) in
//this is for configuring the text field the user will see
textField.borderStyle = UITextField.BorderStyle.bezel
}
alert.addAction(UIAlertAction(title: "OK", style: .default)
{ action in
//use this space to transfer any data
let textField = alert.textFields![0]
self.someStringVariable = textField.text ?? ""
})
self.present(alert, animated: true)
{
//this will run once the action of **presenting** the view
//is complete, rather than when the presented view has been
//dismissed
}
}
override viewDidLoad()
{
super.viewDidLoad()
self.presentAnAlert()
print(self.someStringVariable)
//prints whatever the user input before pressing the OK button
}
}
I hope that helped!