How to sort UIView when keyboard appears? - ios

I can't find a good solution of how to move UIView up when the keyboard appears. My solution now is this:
import UIKit
class LoginViewControllerbybys: UIViewController, UITextFieldDelegate {
// Create username and password text boxes
let emailTextField: UITextField = {
let field = UITextField()
field.placeholder = "EMAIL"
field.font = UIFont(name: "Helvetica Neue", size: 14)
field.background = UIImage(named: "divider")
field.autocapitalizationType = .none
field.autocorrectionType = .no
field.spellCheckingType = .no
field.translatesAutoresizingMaskIntoConstraints = false
return field
}()
let passwordTextField: UITextField = {
let field = UITextField()
field.placeholder = "PASSWORD"
field.font = UIFont(name: "Helvetica Neue", size: 14)
field.background = UIImage(named: "divider")
field.autocapitalizationType = .none
field.autocorrectionType = .no
field.spellCheckingType = .no
field.isSecureTextEntry = true
field.translatesAutoresizingMaskIntoConstraints = false
return field
}()
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .white // sets background colour to white
//Adding notifies on keyboard appearing
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(notification:)), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide(notification:)), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
// Adding Logo in the centre-top of the screen
let logo: UIImageView = {
let image = UIImage(named: "logo")
let imageView = UIImageView(image: image)
imageView.translatesAutoresizingMaskIntoConstraints = false
return imageView
}()
func logoView() {
logo.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
logo.heightAnchor.constraint(equalToConstant: 75).isActive = true
logo.widthAnchor.constraint(equalToConstant: 75).isActive = true
logo.topAnchor.constraint(equalTo: view.topAnchor, constant: 30).isActive = true
}
func emailTextFieldView() {
emailTextField.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
emailTextField.heightAnchor.constraint(equalToConstant: 35).isActive = true
emailTextField.widthAnchor.constraint(equalToConstant: 310).isActive = true
emailTextField.topAnchor.constraint(equalTo: logo.bottomAnchor, constant: 50).isActive = true
}
func passwordTextFieldView() {
passwordTextField.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
passwordTextField.heightAnchor.constraint(equalToConstant: 35).isActive = true
passwordTextField.widthAnchor.constraint(equalToConstant: 310).isActive = true
passwordTextField.topAnchor.constraint(equalTo: emailTextField.bottomAnchor, constant: 30).isActive = true
}
// Create Sign In button
let signInButton: UIButton = {
let button = UIButton()
button.setImage(#imageLiteral(resourceName: "goButton"), for: .normal)
button.frame = CGRect(x: 0, y: 597, width: 375, height: 70)
button.addTarget(self, action: #selector(signInButtonTapped), for: .touchUpInside) // when tapped on Sign In button, execute function SignInTapped
button.translatesAutoresizingMaskIntoConstraints = false
return button
}()
func signInButtonView() {
signInButton.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
signInButton.heightAnchor.constraint(equalToConstant: 70).isActive = true
signInButton.widthAnchor.constraint(equalTo: view.widthAnchor, constant: 0).isActive = true
signInButton.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: 0).isActive = true
}
// Show all Subviews
self.view.addSubview(logo)
self.view.addSubview(signInButton)
self.view.addSubview(emailTextField)
self.view.addSubview(passwordTextField)
// Constraints
logoView()
signInButtonView()
emailTextFieldView()
passwordTextFieldView()
}
func keyboardWillShow(notification: NSNotification) {
let keyboardSize: CGSize = ((notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue.size)!
let offset: CGSize = ((notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue.size)!
if keyboardSize.height == offset.height {
if self.view.frame.origin.y == 0 {
UIView.animate(withDuration: 0.1, animations: { () -> Void in
self.view.frame.origin.y -= keyboardSize.height
})
}
} else {
UIView.animate(withDuration: 0.1, animations: { () -> Void in
self.view.frame.origin.y += keyboardSize.height - offset.height
})
}
}
func keyboardWillHide(notification: NSNotification) {
let keyboardSize: CGSize = ((notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue.size)!
self.view.frame.origin.y += keyboardSize.height
}
}
However, the problem with this is that it hides some of my boxes and a label and I can't see them. I thik I would be able to avoid it with UIScrollView but I have no idea how to do it... Would appreciate any help!

You can use UITableView, then you can focus on the selected row using:
scrollToRow(at:at:animated:)
https://developer.apple.com/reference/uikit/uitableview/1614997-scrolltorow

Related

Swift - Subviews frame.maxY reading incorrectly

I have a basic sign up screen set up programmatically with the UI elements inside a view that is itself inside a scroll view.
The last UI element in the screen is a register button. I set up a keyboard notification observer with the Will Show and Will Hide notifications.
I am running this code on iPod touch 7th gen simulator.
My problem is when trying to read the maxY value of the sign up button and compare it to the keyboard minY it prints wrong numbers.
The keyboard is clearly blocking the register button which mean the button's maxY value will be greater the the keyboard minY value.
However the values printed shows that there is something wrong with the reading of the register button frame.
Here is my code:
import UIKit
class RegisterVC: UIViewController {
private let scrollView: UIScrollView = {
let scroll = UIScrollView()
scroll.clipsToBounds = true
scroll.isScrollEnabled = true
scroll.translatesAutoresizingMaskIntoConstraints = false
scroll.showsVerticalScrollIndicator = false
return scroll
}()
private let scrollInnerView: UIView = {
let innerView = UIView()
innerView.translatesAutoresizingMaskIntoConstraints = false
return innerView
}()
private let profilePic: UIImageView = {
let imageView = UIImageView()
imageView.image = UIImage(systemName: "person.circle")
imageView.contentMode = .scaleAspectFit
imageView.tintColor = .gray
imageView.translatesAutoresizingMaskIntoConstraints = false
return imageView
}()
private let usernameField: UITextField = {
let field = UITextField()
field.autocapitalizationType = .none
field.autocorrectionType = .no
field.returnKeyType = .next
field.layer.cornerRadius = 12
field.layer.borderWidth = 1
field.layer.borderColor = UIColor.lightGray.cgColor
field.placeholder = "Username..."
field.leftView = UIView(frame: CGRect(x: 0, y: 0, width: 5, height: 0))
field.leftViewMode = .always
field.backgroundColor = .white
field.keyboardType = .default
field.isHighlighted = false
field.textAlignment = .left
field.translatesAutoresizingMaskIntoConstraints = false
return field
}()
private let emailField: UITextField = {
let field = UITextField()
field.autocapitalizationType = .none
field.autocorrectionType = .no
field.returnKeyType = .next
field.layer.cornerRadius = 12
field.layer.borderWidth = 1
field.layer.borderColor = UIColor.lightGray.cgColor
field.placeholder = "Email Address..."
field.leftView = UIView(frame: CGRect(x: 0, y: 0, width: 5, height: 0))
field.leftViewMode = .always
field.backgroundColor = .white
field.keyboardType = .default
field.textAlignment = .left
field.translatesAutoresizingMaskIntoConstraints = false
return field
}()
private let passwordField: UITextField = {
let field = UITextField()
field.autocapitalizationType = .none
field.autocorrectionType = .no
field.returnKeyType = .done
field.layer.cornerRadius = 12
field.layer.borderWidth = 1
field.layer.borderColor = UIColor.lightGray.cgColor
field.placeholder = "Password..."
field.leftView = UIView(frame: CGRect(x: 0, y: 0, width: 5, height: 0))
field.leftViewMode = .always
field.backgroundColor = .white
field.isSecureTextEntry = true
field.textAlignment = .left
field.keyboardType = .default
field.translatesAutoresizingMaskIntoConstraints = false
return field
}()
private let registerButton: UIButton = {
let button = UIButton()
button.setTitle("Create Account", for: .normal)
button.backgroundColor = .systemGreen
button.setTitleColor(.white, for: .normal)
button.layer.cornerRadius = 12
button.layer.masksToBounds = true
button.titleLabel?.font = .systemFont(ofSize: 20, weight: .bold)
button.translatesAutoresizingMaskIntoConstraints = false
return button
}()
override func viewDidLoad() {
super.viewDidLoad()
title = "Create Account"
view.backgroundColor = .white
view.addSubview(scrollView)
scrollView.addSubview(scrollInnerView)
scrollInnerView.addSubview(profilePic)
scrollInnerView.addSubview(usernameField)
scrollInnerView.addSubview(emailField)
scrollInnerView.addSubview(passwordField)
scrollInnerView.addSubview(registerButton)
usernameField.delegate = self
emailField.delegate = self
passwordField.delegate = self
profilePic.isUserInteractionEnabled = true
registerButton.addTarget(self,
action: #selector(registerButtonTapped),
for: .touchUpInside)
setUpKeyboard()
setUpConstraints()
}
private func setUpConstraints() {
// Scroll View Constraints
scrollView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor).isActive = true
scrollView.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true
scrollView.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true
scrollView.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor).isActive = true
// Scroll Inner View Constraints
scrollInnerView.topAnchor.constraint(equalTo: scrollView.topAnchor).isActive = true
scrollInnerView.leadingAnchor.constraint(equalTo: scrollView.leadingAnchor).isActive = true
scrollInnerView.trailingAnchor.constraint(equalTo: scrollView.trailingAnchor).isActive = true
scrollInnerView.bottomAnchor.constraint(equalTo: scrollView.bottomAnchor).isActive = true
scrollInnerView.widthAnchor.constraint(equalTo: scrollView.widthAnchor).isActive = true
scrollInnerView.heightAnchor.constraint(equalTo: scrollView.heightAnchor, constant: 1).isActive = true
// Profile Picture Constraints
profilePic.widthAnchor.constraint(equalTo: scrollInnerView.widthAnchor, multiplier: 1/3).isActive = true
profilePic.heightAnchor.constraint(equalTo: scrollInnerView.widthAnchor, multiplier: 1/3).isActive = true
profilePic.centerXAnchor.constraint(equalTo: scrollInnerView.centerXAnchor).isActive = true
profilePic.topAnchor.constraint(equalTo: scrollInnerView.topAnchor, constant: 10).isActive = true
// User Name Field Constraints
usernameField.widthAnchor.constraint(equalTo: scrollInnerView.widthAnchor, constant: -60).isActive = true
usernameField.heightAnchor.constraint(equalToConstant: 45).isActive = true
usernameField.topAnchor.constraint(equalTo: profilePic.bottomAnchor, constant: 10).isActive = true
usernameField.centerXAnchor.constraint(equalTo: profilePic.centerXAnchor).isActive = true
// Email Field Constraints
emailField.widthAnchor.constraint(equalTo: usernameField.widthAnchor).isActive = true
emailField.heightAnchor.constraint(equalTo: usernameField.heightAnchor).isActive = true
emailField.topAnchor.constraint(equalTo: usernameField.bottomAnchor, constant: 10).isActive = true
emailField.centerXAnchor.constraint(equalTo: usernameField.centerXAnchor).isActive = true
// Password Field Constraints
passwordField.widthAnchor.constraint(equalTo: emailField.widthAnchor).isActive = true
passwordField.heightAnchor.constraint(equalTo: emailField.heightAnchor).isActive = true
passwordField.topAnchor.constraint(equalTo: emailField.bottomAnchor, constant: 10).isActive = true
passwordField.centerXAnchor.constraint(equalTo: emailField.centerXAnchor).isActive = true
// Register Button Constraints
registerButton.widthAnchor.constraint(equalTo: passwordField.widthAnchor).isActive = true
registerButton.heightAnchor.constraint(equalTo: passwordField.heightAnchor).isActive = true
registerButton.topAnchor.constraint(equalTo: passwordField.bottomAnchor, constant: 20).isActive = true
registerButton.centerXAnchor.constraint(equalTo: passwordField.centerXAnchor).isActive = true
}
private func setUpKeyboard() {
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShowNotification), name: UIResponder.keyboardWillShowNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHideNotification), name: UIResponder.keyboardWillHideNotification, object: nil)
}
#objc private func keyboardWillShowNotification(_ notification: NSNotification) {
guard let keyboardSize = (notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue
else {
return
}
print(keyboardSize.minY)
print(registerButton.frame.maxY)
}
}
It's because the keyboard frame and the button frame are in two different coordinate systems. You cannot compare them directly. You need to convert the button frame to window coordinates before comparing them. Or else convert the keyboard frame to the button frame coordinates (the button's superview).
Actually what I typically do is convert the keyboard frame to the internal coordinates of the target view and compare that to the target view's bounds. For example:
// n is the notification
let d = n.userInfo!
var r = d[UIResponder.keyboardFrameEndUserInfoKey] as! CGRect
r = self.slidingView.convert(r, from:nil) // <- this is the key move!
let h = self.slidingView.bounds.intersection(r).height
That tells me whether the keyboard would cover the sliding view, and if so, by how much.

Passing Data from one ViewController to Another Programmatically, Swift [duplicate]

This question already has answers here:
How to pass data from modal view controller back when dismissed
(4 answers)
Closed 2 years ago.
I just want to transfer some data between two ViewControllers and also wrote some Code. But, if I update my tableView, the user-given data isn't presented at the tableView. Can anyone help me?
import UIKit
import CoreData
class AddNewRecipeViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
private let reuseIdentifer = "IngredientCell"
let pressGesture = UILongPressGestureRecognizer()
let titleLabel = UILabel()
let tf_one = UITextField()
let tf_two = UITextField()
let tableView = UITableView()
let submitButton = UIButton()
let newButton = UIButton()
var name_array = [String]()
var unit_array = [String]()
var quantity_array = [String]()
let recipeId = Int.random(in: 0...5000)
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .white
createViewControllerItems()
}
#objc func refresh(){
print(name_array)
self.tableView.reloadData()
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
self.view.endEditing(true)
}
#objc func dismissKeyboard() {
view.endEditing(true)
}
func createViewControllerItems() {
// - MARK: Titel
titleLabel.text = "Neues Rezept"
titleLabel.textColor = .black
titleLabel.textAlignment = .center
titleLabel.font = UIFont(name: "Bradley Hand", size: 24)
view.addSubview(titleLabel)
titleLabel.translatesAutoresizingMaskIntoConstraints = false
titleLabel.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
titleLabel.topAnchor.constraint(equalTo: view.topAnchor, constant: 30).isActive = true
titleLabel.widthAnchor.constraint(equalToConstant: 200).isActive = true
titleLabel.heightAnchor.constraint(equalToConstant: 40).isActive = true
newButton.setTitle("test", for: UIControl.State.normal)
newButton.setTitleColor(.black, for: UIControl.State.normal)
newButton.addTarget(self, action: #selector(refresh), for: .touchUpInside)
view.addSubview(newButton)
newButton.translatesAutoresizingMaskIntoConstraints = false
newButton.leftAnchor.constraint(equalTo: view.leftAnchor, constant: 30).isActive = true
newButton.topAnchor.constraint(equalTo: view.topAnchor, constant: 30).isActive = true
newButton.widthAnchor.constraint(equalToConstant: 40).isActive = true
newButton.heightAnchor.constraint(equalToConstant: 40).isActive = true
// - MARK: Überschrift
tf_one.placeholder = "Name"
tf_one.borderStyle = .roundedRect
tf_one.keyboardType = .default
tf_one.spellCheckingType = .yes
tf_one.smartInsertDeleteType = .yes
tf_one.autocorrectionType = .yes
tf_one.autocapitalizationType = .sentences
view.addSubview(tf_one)
tf_one.translatesAutoresizingMaskIntoConstraints = false
tf_one.leftAnchor.constraint(equalTo: view.leftAnchor, constant: 15).isActive = true
tf_one.topAnchor.constraint(equalTo: view.topAnchor, constant: 100).isActive = true
tf_one.widthAnchor.constraint(equalToConstant: 270).isActive = true
tf_one.heightAnchor.constraint(equalToConstant: 34).isActive = true
// - MARK: Anzahl Portionen
tf_two.placeholder = "Anzahl"
tf_two.borderStyle = .roundedRect
tf_two.keyboardType = .decimalPad
view.addSubview(tf_two)
tf_two.translatesAutoresizingMaskIntoConstraints = false
tf_two.topAnchor.constraint(equalTo: view.topAnchor, constant: 100).isActive = true
tf_two.leftAnchor.constraint(equalTo: tf_one.rightAnchor, constant: 3).isActive = true
tf_two.widthAnchor.constraint(equalToConstant: 70).isActive = true
tf_two.heightAnchor.constraint(equalToConstant: 34).isActive = true
// - MARK: Table View
tableView.delegate = self
tableView.dataSource = self
tableView.register(IngredientCell.self, forCellReuseIdentifier: reuseIdentifer)
tableView.rowHeight = 55
view.addSubview(tableView)
tableView.translatesAutoresizingMaskIntoConstraints = false
tableView.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true
tableView.rightAnchor.constraint(equalTo: view.rightAnchor).isActive = true
tableView.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: -100).isActive = true
tableView.topAnchor.constraint(equalTo: tf_one.bottomAnchor, constant: 10).isActive = true
// - MARK: Bestätigen
submitButton.layer.cornerRadius = 20
submitButton.clipsToBounds = true
submitButton.backgroundColor = .lightGray
submitButton.setTitle("ok", for: UIControl.State.normal)
submitButton.setTitleColor(.white, for: UIControl.State.normal)
submitButton.titleLabel?.font = UIFont(name: "Chalkduster", size: 24)
submitButton.addTarget(self, action: #selector(save), for: .touchUpInside)
view.addSubview(submitButton)
submitButton.translatesAutoresizingMaskIntoConstraints = false
submitButton.rightAnchor.constraint(equalTo: view.rightAnchor, constant: -30).isActive = true
submitButton.topAnchor.constraint(equalTo: view.topAnchor, constant: 30).isActive = true
submitButton.widthAnchor.constraint(equalToConstant: 40).isActive = true
submitButton.heightAnchor.constraint(equalToConstant: 40).isActive = true
// - MARK: Add Gesture
pressGesture.addTarget(self, action: #selector(pressAction))
view.addGestureRecognizer(pressGesture)
}
#objc func pressAction() {
let generator = UIImpactFeedbackGenerator(style: .heavy)
generator.impactOccurred()
let vc: AddNewIngredientViewController!
vc = AddNewIngredientViewController()
vc.modalPresentationStyle = .automatic
self.present(vc, animated: true)
}
#objc func save() {
//save befor dismiss
dismiss(animated: true, completion: nil)
/*
guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else {
return
}
let context = appDelegate.persistentContainer.viewContext
let entityName = "Recipes"
guard let newEntity = NSEntityDescription.entity(forEntityName: entityName, in: context) else {
return
}
let newRecipe = NSManagedObject(entity: newEntity, insertInto: context)
let name = tf_one.text
let id = recipeId
let category = 1
let persons = 2
newRecipe.setValue(name, forKey: "name")
newRecipe.setValue(id, forKey: "id")
newRecipe.setValue(category, forKey: "category")
newRecipe.setValue(persons, forKey: "persons")
do {
try context.save()
print("Gespeichert!")
let vc: ViewController!
vc = ViewController()
vc.modalPresentationStyle = .fullScreen
self.present(vc, animated: false)
} catch {
print(error)
}*/
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
print(name_array.count)
return name_array.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: reuseIdentifer, for: indexPath) as! IngredientCell
cell.nameLabel.text = name_array[indexPath.row]
cell.descriptionLabel.text = "text"
cell.personsLabel.text = "text"
return cell
}
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else {
return
}
let context = appDelegate.persistentContainer.viewContext
let entityName = "/ENTRY/"
let request = NSFetchRequest<NSFetchRequestResult>(entityName: entityName)
do {
let results = try context.fetch(request)
guard results.count > 0 else {
return
}
if let deleteEntity = results[indexPath.row] as? NSManagedObject {
context.delete(deleteEntity) //Das Entity ist hier nur markiert als gelöscht, für evt arbeiten am Item
if context.hasChanges {
do {
try context.save()
print("Datensatz gelöscht!")
let vc: ViewController!
vc = ViewController()
vc.modalPresentationStyle = .fullScreen
self.present(vc, animated: false)
} catch {
print(error)
}
}
}
} catch {
print(error)
}
}
}
}
import UIKit
import CoreData
class AddNewIngredientViewController: UIViewController {
let viewExample = UIView()
let titleLabel = UILabel()
let tf_one = UITextField()
let unitTicker = UISegmentedControl()
let unitLabel = UILabel()
let slider = UISlider()
let submitButton = UIButton()
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.white.withAlphaComponent(0)
createViewControllerItems()
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
self.view.endEditing(true)
}
#objc func dismissKeyboard() {
view.endEditing(true)
}
func createViewControllerItems() {
// - MARK: View
viewExample.backgroundColor = .white
viewExample.layer.cornerRadius = 15
viewExample.clipsToBounds = true
view.addSubview(viewExample)
viewExample.translatesAutoresizingMaskIntoConstraints = false
viewExample.centerYAnchor.constraint(equalTo: view.centerYAnchor, constant: -200).isActive = true
viewExample.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
viewExample.widthAnchor.constraint(equalToConstant: 330).isActive = true
viewExample.heightAnchor.constraint(equalToConstant: 350).isActive = true
// - MARK: Titel
titleLabel.text = "Zutat hinzufügen"
titleLabel.textColor = .black
titleLabel.textAlignment = .center
titleLabel.font = UIFont(name: "Chalkduster", size: 24)
view.addSubview(titleLabel)
titleLabel.translatesAutoresizingMaskIntoConstraints = false
titleLabel.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
titleLabel.topAnchor.constraint(equalTo: view.topAnchor, constant: 50).isActive = true
titleLabel.widthAnchor.constraint(equalToConstant: 250).isActive = true
titleLabel.heightAnchor.constraint(equalToConstant: 40).isActive = true
// - MARK: Überschrift
tf_one.placeholder = "Name"
tf_one.borderStyle = .roundedRect
tf_one.keyboardType = .default
tf_one.spellCheckingType = .yes
tf_one.smartInsertDeleteType = .yes
tf_one.autocorrectionType = .yes
tf_one.autocapitalizationType = .sentences
view.addSubview(tf_one)
tf_one.translatesAutoresizingMaskIntoConstraints = false
tf_one.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
tf_one.topAnchor.constraint(equalTo: view.topAnchor, constant: 100).isActive = true
tf_one.widthAnchor.constraint(equalToConstant: 310).isActive = true
tf_one.heightAnchor.constraint(equalToConstant: 34).isActive = true
// - MARK: Unit Ticker
unitTicker.insertSegment(withTitle: "ml", at: 0, animated: true)
unitTicker.insertSegment(withTitle: "mg", at: 1, animated: true)
unitTicker.insertSegment(withTitle: "unit", at: 2, animated: true)
unitTicker.addTarget(self, action: #selector(updateLabel), for: UIControl.Event.allEvents)
view.addSubview(unitTicker)
unitTicker.translatesAutoresizingMaskIntoConstraints = false
unitTicker.topAnchor.constraint(equalTo: view.topAnchor, constant: 150).isActive = true
unitTicker.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
// - MARK: Slider
slider.maximumValue = 10
slider.addTarget(self, action: #selector(updateLabel), for: UIControl.Event.allEvents)
view.addSubview(slider)
slider.translatesAutoresizingMaskIntoConstraints = false
slider.topAnchor.constraint(equalTo: view.topAnchor, constant: 200).isActive = true
slider.widthAnchor.constraint(equalToConstant: 310).isActive = true
slider.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
// - MARK: Bestätigen
submitButton.layer.cornerRadius = 20
submitButton.clipsToBounds = true
submitButton.backgroundColor = .lightGray
submitButton.setTitle("ok", for: UIControl.State.normal)
submitButton.titleLabel?.font = UIFont(name: "Chalkduster", size: 24)
submitButton.addTarget(self, action: #selector(save), for: .touchUpInside)
view.addSubview(submitButton)
submitButton.translatesAutoresizingMaskIntoConstraints = false
submitButton.centerXAnchor.constraint(equalTo: view.centerXAnchor, constant: 100).isActive = true
submitButton.topAnchor.constraint(equalTo: slider.bottomAnchor, constant: 50).isActive = true
submitButton.widthAnchor.constraint(equalToConstant: 40).isActive = true
submitButton.heightAnchor.constraint(equalToConstant: 40).isActive = true
}
#objc func updateLabel() {
unitLabel.textAlignment = .center
if unitTicker.selectedSegmentIndex == 0{
unitLabel.text = "\(Int(slider.value)) ml"
slider.maximumValue = 1000
}else if unitTicker.selectedSegmentIndex == 1{
unitLabel.text = "\(Int(slider.value)) mg"
slider.maximumValue = 1000
}else if unitTicker.selectedSegmentIndex == 2{
unitLabel.text = "\(Int(slider.value)) unit"
slider.maximumValue = 10
}
view.addSubview(unitLabel)
unitLabel.translatesAutoresizingMaskIntoConstraints = false
unitLabel.topAnchor.constraint(equalTo: view.topAnchor, constant: 230).isActive = true
unitLabel.widthAnchor.constraint(equalToConstant: 310).isActive = true
unitLabel.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
}
#objc func save() {
let viewController = AddNewRecipeViewController()
viewController.name_array.append(tf_one.text!)
print(viewController.name_array)
dismiss(animated: true, completion: nil)
}
}
Thanks!
Tom
You can pass data between two viewController by using the delegate method or NSNotificaton. For more info visit about NSNotification: https://developer.apple.com/documentation/foundation/nsnotification
For delegate method you can check https://medium.com/#jamesrochabrun/implementing-delegates-in-swift-step-by-step-d3211cbac3ef

How can I get a button in my subview to enable the rightbarbuttonitem in my view controller

I have a UIView with a textfield and a button, this UIView is a subview of my view controller. How can I have the button in my subview enable the view controller's navigation rightbarbuttonitem when it is pressed?
class CreateActivityView: UIView {
override init(frame: CGRect) {
super.init(frame: frame)
setupView()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
lazy var addButton: UIButton = {
let button = UIButton(type: UIButton.ButtonType.system)
button.setImage(UIImage(named: "add_dark.png"), for: .normal)
button.frame = CGRect(x: 0, y: 0, width: 24.0, height: 24.0)
button.addTarget(self, action: #selector(addButtonTapped), for: .touchUpInside)
button.isEnabled = false
button.translatesAutoresizingMaskIntoConstraints = false
return button
}()
lazy var activityNameTextField: DataEntryTextField = {
let textField = DataEntryTextField()
textField.frame = CGRect(x: 0, y: 0, width: 250.0, height: 30.0)
textField.placeholder = "Add an activity"
textField.font = UIFont(name: "Avenir", size: 17)
textField.keyboardType = UIKeyboardType.default
textField.returnKeyType = UIReturnKeyType.done
textField.translatesAutoresizingMaskIntoConstraints = false
return textField
}()
lazy var activityNameLabel: UILabel = {
let label = UILabel()
label.frame = CGRect(x: 0, y: 0, width: 0, height: 30.0)
label.font = UIFont(name: "Avenir", size: 17)
label.translatesAutoresizingMaskIntoConstraints = false
label.isHidden = true
return label
}()
func setupView() {
backgroundColor = UIColor.lightGray
addSubview(addButton)
addButton.rightAnchor.constraint(equalTo: self.safeAreaLayoutGuide.rightAnchor, constant: -16.0).isActive = true
addButton.centerYAnchor.constraint(equalTo: self.safeAreaLayoutGuide.centerYAnchor).isActive = true
addButton.heightAnchor.constraint(equalToConstant: 24.0).isActive = true
addButton.widthAnchor.constraint(equalToConstant: 24.0).isActive = true
addSubview(activityNameTextField)
activityNameTextField.leftAnchor.constraint(equalTo: self.safeAreaLayoutGuide.leftAnchor, constant: 16.0).isActive = true
activityNameTextField.topAnchor.constraint(equalTo: self.safeAreaLayoutGuide.topAnchor, constant: 10.0).isActive = true
activityNameTextField.bottomAnchor.constraint(equalTo: self.safeAreaLayoutGuide.bottomAnchor, constant: -10.0).isActive = true
activityNameTextField.rightAnchor.constraint(equalTo: addButton.safeAreaLayoutGuide.leftAnchor, constant: -20.0).isActive = true
addSubview(activityNameLabel)
activityNameLabel.leftAnchor.constraint(equalTo: self.safeAreaLayoutGuide.leftAnchor, constant: 16.0).isActive = true
activityNameLabel.rightAnchor.constraint(equalTo: self.safeAreaLayoutGuide.rightAnchor, constant: -16.0).isActive = true
activityNameLabel.topAnchor.constraint(equalTo: self.safeAreaLayoutGuide.topAnchor, constant: 10.0).isActive = true
activityNameLabel.bottomAnchor.constraint(equalTo: self.safeAreaLayoutGuide.bottomAnchor, constant: -10.0).isActive = true
}
#objc func addButtonTapped() {
guard let validatedText = activityNameTextField.text?.trimmingCharacters(in: .whitespacesAndNewlines), !validatedText.isEmpty else {
return
}
displayActivityNameLabel(with: validatedText)
}
func displayActivityNameLabel(with text: String) {
activityNameLabel.text = text
activityNameLabel.isHidden = false
activityNameTextField.isHidden = true
print(activityNameLabel.text)
}
}
class QuickLogViewController: UIViewController {
let screenSize = UIScreen.main.bounds.size
var createActivityView: CreateActivityView!
override func viewDidLoad() {
super.viewDidLoad()
title = "Quick Log"
setupView()
}
func setupView() {
initializeCreateActivityView()
self.view.addSubview(createActivityView)
createActivityView.leftAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.leftAnchor).isActive = true
createActivityView.rightAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.rightAnchor).isActive = true
createActivityView.topAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.topAnchor).isActive = true
createActivityView.heightAnchor.constraint(equalToConstant: 50.0).isActive = true
}
func initializeCreateActivityView() {
createActivityView = CreateActivityView()
createActivityView.frame = CGRect(x: 0, y: 0, width: screenSize.width, height: 50.0)
createActivityView.translatesAutoresizingMaskIntoConstraints = false
createActivityView.activityNameTextField.delegate = self
}
func enableCancelButton() {
navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .cancel, target: self, action: #selector(cancelButtonPressed))
}
}
I added my CreateActivityView to my view controller. The button target is handled by my createActvitiyView. So how can I access the rightbarbuttonitem from the subview?
You can try to use delegate
class CreateActivityView: UIView {
weak var delegate:VCName?
and
createActivityView = CreateActivityView()
createActivityView.delegate = self
after that inside any action do
delegate?.methodInsideTheVC()
Or write button action inside the vc
createActivityView = CreateActivityView()
createActivityView.button.addTarget(self, action: #selector(addButtonTapped), for: .touchUpInside)
and place
#objc func addButtonTapped() {

swift can't call function after clicking button

I have made a container view with a image view and a button inside for some reason when running the app in simulator i can't click button and call the function taking me to the next screen , i have encountered this kind of problem before and it was as simple as changing the button to a lazy var though that hasn't work on this occasion?
lazy var nameLabelButton = UIButton()
func setupNavBarWithUser() {
guard let displayName = user?.DisplayName else { return }
let titleView = UIView()
titleView.frame = CGRect(x: 0, y: 0, width: 100, height: 40)
titleView.backgroundColor = UIColor.red
let containerView = UIView()
containerView.translatesAutoresizingMaskIntoConstraints = false
titleView.addSubview(containerView)
let profileImageView = UIImageView()
profileImageView.translatesAutoresizingMaskIntoConstraints = false
profileImageView.contentMode = .scaleAspectFill
profileImageView.layer.cornerRadius = 20
profileImageView.clipsToBounds = true
if let profileImageUrl = user?.profileImageURL {
profileImageView.loadImageUsingCacheWithUrlString(urlString:profileImageUrl)
}
containerView.addSubview(profileImageView)
//ios 9 constraint anchors
//need x,y,width,height anchors
profileImageView.leftAnchor.constraint(equalTo: containerView.leftAnchor).isActive = true
profileImageView.centerYAnchor.constraint(equalTo: containerView.centerYAnchor).isActive = true
profileImageView.widthAnchor.constraint(equalToConstant: 40).isActive = true
profileImageView.heightAnchor.constraint(equalToConstant: 40).isActive = true
containerView.addSubview(nameLabelButton)
nameLabelButton.setTitle("\(displayName)", for: .normal)
nameLabelButton.setTitleColor(.black, for: .normal)
nameLabelButton.translatesAutoresizingMaskIntoConstraints = false
//need x,y,width,height anchors
nameLabelButton.leftAnchor.constraint(equalTo: profileImageView.rightAnchor, constant: 8).isActive = true
nameLabelButton.centerYAnchor.constraint(equalTo: profileImageView.centerYAnchor).isActive = true
nameLabelButton.rightAnchor.constraint(equalTo: containerView.rightAnchor).isActive = true
nameLabelButton.heightAnchor.constraint(equalTo: profileImageView.heightAnchor).isActive = true
containerView.centerXAnchor.constraint(equalTo: titleView.centerXAnchor).isActive = true
containerView.centerYAnchor.constraint(equalTo: titleView.centerYAnchor).isActive = true
nameLabelButton.addTarget(self, action: #selector(self.openUsersProfileController), for: .touchUpInside)
self.navigationItem.titleView = titleView
}
func openUsersProfileController(){
print("asdasdadsad")
let openUsersProfileController = UserProfileController(collectionViewLayout: UICollectionViewFlowLayout())
openUsersProfileController.user = self.user
navigationController?.pushViewController(openUsersProfileController, animated: true)
}
well, code looks fine you just need to add #objc
#objc func openUsersProfileController(){
print("asdasdadsad")
let openUsersProfileController = UserProfileController(collectionViewLayout: UICollectionViewFlowLayout())
openUsersProfileController.user = self.user
navigationController?.pushViewController(openUsersProfileController, animated: true)
}
Reason:
From Swift 4, we manually need to add #objc before function.

How can i use activity indicator when a user registers or login messageView using swift 3

How can i use activity Indicator in the following code when a user registers or logs in the message view.
The Code below is a loginViewController which handles the login and Registeration of the User.
so, How can i use Activity Indicator View or Progress view PROGRAMATICALLY whenever a user hits the Login or Register Button .
class LoginController: UIViewController {
var messagesController: MessagesController?
let inputsContainerView: UIView = {
let view = UIView()
view.backgroundColor = UIColor(r: 209, g:238, b:252).withAlphaComponent(0.3)
view.translatesAutoresizingMaskIntoConstraints = false
view.layer.cornerRadius = 5
view.layer.masksToBounds = true
return view
}()
lazy var loginRegisterButton: UIButton = {
let button = UIButton(type: .system)
button.backgroundColor = UIColor(r: 255, g: 45, b: 85)
button.setTitle("Register", for: UIControlState())
button.translatesAutoresizingMaskIntoConstraints = false
button.setTitleColor(UIColor.white, for: UIControlState())
button.titleLabel?.font = UIFont.boldSystemFont(ofSize: 16)
button.layer.cornerRadius = 10
button.addTarget(self, action: #selector(handleLoginRegister), for: .touchUpInside)
return button
}()
func handleLoginRegister() {
if loginRegisterSegmentedControl.selectedSegmentIndex == 0 {
handleLogin()
} else {
handleRegister()
}
}
func handleLogin() {
guard let email = emailTextField.text, let password = passwordTextField.text else {
print("Form is not valid")
return
}
FIRAuth.auth()?.signIn(withEmail: email, password: password, completion: { (user, error) in
if error != nil {
print(error ?? "")
return
}
//successfully logged in our user
self.messagesController?.fetchUserAndSetupNavBarTitle()
self.dismiss(animated: true, completion: nil)
})
}
// TextField, EmailTextField, PasswordTextField, seperator view
let nameTextField: UITextField = {
let tf = UITextField()
tf.placeholder = "Name"
tf.translatesAutoresizingMaskIntoConstraints = false
return tf
}()
let nameSeparatorView: UIView = {
let view = UIView()
view.backgroundColor = UIColor(r: 220, g: 220, b: 220)
view.translatesAutoresizingMaskIntoConstraints = false
return view
}()
let emailTextField: UITextField = {
let tf = UITextField()
tf.placeholder = "Email"
tf.translatesAutoresizingMaskIntoConstraints = false
return tf
}()
let emailSeparatorView: UIView = {
let view = UIView()
view.backgroundColor = UIColor(r: 220, g: 220, b: 220)
view.translatesAutoresizingMaskIntoConstraints = false
return view
}()
let passwordTextField: UITextField = {
let tf = UITextField()
tf.placeholder = "Password"
tf.translatesAutoresizingMaskIntoConstraints = false
tf.isSecureTextEntry = true
return tf
}()
lazy var profileImageView: UIImageView = {
let imageView = UIImageView()
imageView.image = UIImage(named: "backslash_inc02main")
imageView.translatesAutoresizingMaskIntoConstraints = false
imageView.contentMode = .scaleAspectFill
imageView.layer.cornerRadius = 20
imageView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(handleSelectProfileImageView)))
imageView.isUserInteractionEnabled = true
return imageView
}()
lazy var loginRegisterSegmentedControl: UISegmentedControl = {
let sc = UISegmentedControl(items: ["Login", "Register"])
sc.translatesAutoresizingMaskIntoConstraints = false
sc.tintColor = UIColor.white
sc.selectedSegmentIndex = 1
sc.addTarget(self, action: #selector(handleLoginRegisterChange), for: .valueChanged)
return sc
}()
func handleLoginRegisterChange() {
let title = loginRegisterSegmentedControl.titleForSegment(at: loginRegisterSegmentedControl.selectedSegmentIndex)
loginRegisterButton.setTitle(title, for: UIControlState())
// change height of inputContainerView, but how???
inputsContainerViewHeightAnchor?.constant = loginRegisterSegmentedControl.selectedSegmentIndex == 0 ? 100 : 150
// change height of nameTextField
nameTextFieldHeightAnchor?.isActive = false
nameTextFieldHeightAnchor = nameTextField.heightAnchor.constraint(equalTo: inputsContainerView.heightAnchor, multiplier: loginRegisterSegmentedControl.selectedSegmentIndex == 0 ? 0 : 1/3)
nameTextFieldHeightAnchor?.isActive = true
nameTextField.isHidden = loginRegisterSegmentedControl.selectedSegmentIndex == 0
emailTextFieldHeightAnchor?.isActive = false
emailTextFieldHeightAnchor = emailTextField.heightAnchor.constraint(equalTo: inputsContainerView.heightAnchor, multiplier: loginRegisterSegmentedControl.selectedSegmentIndex == 0 ? 1/2 : 1/3)
emailTextFieldHeightAnchor?.isActive = true
passwordTextFieldHeightAnchor?.isActive = false
passwordTextFieldHeightAnchor = passwordTextField.heightAnchor.constraint(equalTo: inputsContainerView.heightAnchor, multiplier: loginRegisterSegmentedControl.selectedSegmentIndex == 0 ? 1/2 : 1/3)
passwordTextFieldHeightAnchor?.isActive = true
}
override func viewDidLoad() {
super.viewDidLoad()
//view.backgroundColor = UIColor(r: 255, g: 149, b: 0)
self.view.addBackground()
view.addSubview(inputsContainerView)
view.addSubview(loginRegisterButton)
view.addSubview(profileImageView)
view.addSubview(loginRegisterSegmentedControl)
setupInputsContainerView()
setupLoginRegisterButton()
setupProfileImageView()
setupLoginRegisterSegmentedControl()
}
func setupLoginRegisterSegmentedControl() {
//need x, y, width, height constraints
loginRegisterSegmentedControl.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
loginRegisterSegmentedControl.bottomAnchor.constraint(equalTo: inputsContainerView.topAnchor, constant: -12).isActive = true
loginRegisterSegmentedControl.widthAnchor.constraint(equalTo: inputsContainerView.widthAnchor, multiplier: 1).isActive = true
loginRegisterSegmentedControl.heightAnchor.constraint(equalToConstant: 36).isActive = true
}
func setupProfileImageView() {
//need x, y, width, height constraints
profileImageView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
profileImageView.bottomAnchor.constraint(equalTo: loginRegisterSegmentedControl.topAnchor, constant: -12).isActive = true
profileImageView.widthAnchor.constraint(equalToConstant: 150).isActive = true
profileImageView.heightAnchor.constraint(equalToConstant: 150).isActive = true
}
var inputsContainerViewHeightAnchor: NSLayoutConstraint?
var nameTextFieldHeightAnchor: NSLayoutConstraint?
var emailTextFieldHeightAnchor: NSLayoutConstraint?
var passwordTextFieldHeightAnchor: NSLayoutConstraint?
func setupInputsContainerView() {
//need x, y, width, height constraints
inputsContainerView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
inputsContainerView.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
inputsContainerView.widthAnchor.constraint(equalTo: view.widthAnchor, constant: -24).isActive = true
inputsContainerViewHeightAnchor = inputsContainerView.heightAnchor.constraint(equalToConstant: 150)
inputsContainerViewHeightAnchor?.isActive = true
inputsContainerView.addSubview(nameTextField)
inputsContainerView.addSubview(nameSeparatorView)
inputsContainerView.addSubview(emailTextField)
inputsContainerView.addSubview(emailSeparatorView)
inputsContainerView.addSubview(passwordTextField)
//need x, y, width, height constraints
nameTextField.leftAnchor.constraint(equalTo: inputsContainerView.leftAnchor, constant: 12).isActive = true
nameTextField.topAnchor.constraint(equalTo: inputsContainerView.topAnchor).isActive = true
nameTextField.widthAnchor.constraint(equalTo: inputsContainerView.widthAnchor).isActive = true
nameTextFieldHeightAnchor = nameTextField.heightAnchor.constraint(equalTo: inputsContainerView.heightAnchor, multiplier: 1/3)
nameTextFieldHeightAnchor?.isActive = true
//need x, y, width, height constraints
nameSeparatorView.leftAnchor.constraint(equalTo: inputsContainerView.leftAnchor).isActive = true
nameSeparatorView.topAnchor.constraint(equalTo: nameTextField.bottomAnchor).isActive = true
nameSeparatorView.widthAnchor.constraint(equalTo: inputsContainerView.widthAnchor).isActive = true
nameSeparatorView.heightAnchor.constraint(equalToConstant: 1).isActive = true
//need x, y, width, height constraints
emailTextField.leftAnchor.constraint(equalTo: inputsContainerView.leftAnchor, constant: 12).isActive = true
emailTextField.topAnchor.constraint(equalTo: nameTextField.bottomAnchor).isActive = true
emailTextField.widthAnchor.constraint(equalTo: inputsContainerView.widthAnchor).isActive = true
emailTextFieldHeightAnchor = emailTextField.heightAnchor.constraint(equalTo: inputsContainerView.heightAnchor, multiplier: 1/3)
emailTextFieldHeightAnchor?.isActive = true
//need x, y, width, height constraints
emailSeparatorView.leftAnchor.constraint(equalTo: inputsContainerView.leftAnchor).isActive = true
emailSeparatorView.topAnchor.constraint(equalTo: emailTextField.bottomAnchor).isActive = true
emailSeparatorView.widthAnchor.constraint(equalTo: inputsContainerView.widthAnchor).isActive = true
emailSeparatorView.heightAnchor.constraint(equalToConstant: 1).isActive = true
//need x, y, width, height constraints
passwordTextField.leftAnchor.constraint(equalTo: inputsContainerView.leftAnchor, constant: 12).isActive = true
passwordTextField.topAnchor.constraint(equalTo: emailTextField.bottomAnchor).isActive = true
passwordTextField.widthAnchor.constraint(equalTo: inputsContainerView.widthAnchor).isActive = true
passwordTextFieldHeightAnchor = passwordTextField.heightAnchor.constraint(equalTo: inputsContainerView.heightAnchor, multiplier: 1/3)
passwordTextFieldHeightAnchor?.isActive = true
}
func setupLoginRegisterButton() {
//need x, y, width, height constraints
loginRegisterButton.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
loginRegisterButton.topAnchor.constraint(equalTo: inputsContainerView.bottomAnchor, constant: 12).isActive = true
loginRegisterButton.widthAnchor.constraint(equalTo: inputsContainerView.widthAnchor).isActive = true
loginRegisterButton.heightAnchor.constraint(equalToConstant: 50).isActive = true
}
override var preferredStatusBarStyle : UIStatusBarStyle {
return .lightContent
}
}
extension UIColor {
convenience init(r: CGFloat, g: CGFloat, b: CGFloat) {
self.init(red: r/255, green: g/255, blue: b/255, alpha: 1)
}
}
To show activity indicator, first declare it at class level and then initialize it.
var activityIndicator:UIActivityIndicatorView!
Then in your viewdidLoad() method, initialize activityIndicator.
activityIndicator = UIActivityIndicatorView(activityIndicatorStyle: .gray)
activityIndicator.center = view.center
activityIndicator.isHidden = true
self.view.addSubview(activityIndicator)
You can write two methods to start and stop activity indicator in your view controller as:
func displayActivityIndicatorView() -> () {
UIApplication.shared.beginIgnoringInteractionEvents()
self.view.bringSubview(toFront: self.activityIndicator)
self.activityIndicator.isHidden = false
self.activityIndicator.startAnimating()
}
func hideActivityIndicatorView() -> () {
if !self.activityIndicator.isHidden{
DispatchQueue.main.async {
UIApplication.shared.endIgnoringInteractionEvents()
self.activityIndicator.stopAnimating()
self.activityIndicator.isHidden = true
}
}
}
Now start activity indicator just after validating the login data and before hitting the login API as:
func handleLogin() {
guard let email = emailTextField.text, let password = passwordTextField.text else {
print("Form is not valid")
return
}
//start activity indicator
self. displayActivityIndicatorView()
FIRAuth.auth()?.signIn(withEmail: email, password: password, completion: { (user, error) in
if error != nil {
print(error ?? "")
//stop activity indicator
self. hideActivityIndicatorView()
return
}
//successfully logged in our user
//stop activity indicator
self. hideActivityIndicatorView()
self.messagesController?.fetchUserAndSetupNavBarTitle()
self.dismiss(animated: true, completion: nil)
})
}
Step 1:
Create activity indicator somewhere in your code. Specially in viewDidLoad
if you want to create it programmatically or if you want to show activity indicator with an alert design in programmatically.
Step 2: To show activity indicator
There is a button like login or register . There you will start the to show the activity indicator and start it to animate.
Step 3: To hide activity indicator
You will hide activity indicator in FIRAuth.auth()?.signIn..... completion handler for login. just like
[indicator stopAnimating];
[indicator isHidden:YES];
There are two cases in that login method. one is error and the other is successful. Its better to show an error alert to the user or something else.
Hope you will find this solution helpful. :)
You can use below code.
let alert = UIAlertController(title: nil, message: "Please wait...", preferredStyle: .alert)
alert.view.tintColor = UIColor.black
let loadingIndicator: UIActivityIndicatorView = UIActivityIndicatorView(frame: CGRect(x:10, y:5, width:50, height:50)) as UIActivityIndicatorView
loadingIndicator.hidesWhenStopped = true
loadingIndicator.activityIndicatorViewStyle = UIActivityIndicatorViewStyle.gray
loadingIndicator.color = UIColor(red: 255.0/255, green: 65.0/255, blue: 42.0/255,alpha : 1.0)
loadingIndicator.startAnimating();
alert.view.addSubview(loadingIndicator)
present(alert, animated: true, completion: nil)
///dismisss///
dismiss(animated: false, completion: nil)

Resources