I'm having a Sign up View controller in storyboard and it keeps showing me the same error in console:
this class is not key value coding-compliant for the key displayNameTextField.
I'm aware that this means that there's a connection that no longer exists and it causing it to crash. The problem is that I don't see any issues whatsoever. This is the View controller in Storyboard along with all the connections:
This is the code:
class SignUpVC: UIViewController
{
#IBOutlet weak var displayNameTextField: UITextField!
#IBOutlet weak var usernameTextField: UITextField!
#IBOutlet weak var emailTextField: UITextField!
#IBOutlet weak var passwordTextField: UITextField!
#IBOutlet weak var registerButton: UIButton!
override func viewDidLoad()
{
super.viewDidLoad()
setupTextFields()
}
func setupTextFields()
{
displayNameTextField.tintColor = UIColor.white
displayNameTextField.textColor = UIColor.white
displayNameTextField.backgroundColor = UIColor(red: 138/255, green: 82/255, blue: 108/255, alpha: 1.0)
displayNameTextField.attributedPlaceholder = NSAttributedString(string : displayNameTextField.placeholder!,
attributes: [NSAttributedStringKey.foregroundColor : UIColor(white: 1.0, alpha: 0.6)])
handleTextFields()
}
func handleTextFields()
{
displayNameTextField.addTarget(self, action: #selector(self.textFieldDidChange), for: .editingChanged)
}
#objc func textFieldDidChange() {
guard let username = usernameTextField.text, !username.isEmpty,
let displayName = displayNameTextField.text, !displayName.isEmpty,
let email = emailTextField.text, !email.isEmpty,
let password = passwordTextField.text, !password.isEmpty
else
{
return
}
registerButton.isEnabled = true
}
}
What am I doing wrong? It's one of those cases where this should be painfully obvious but I just don't see it.
This error is usually an indication that you haven’t set the subclass of the view controller correctly.
Check in the attributes inspector in interface builder for that view controller.
Related
I'm new to swift, I would like to change my UIViewController background color from the custom UIToolbar that I already created at XIB. I also already add the custom toolbar to my keyboard. How can i do that?
In my toolbar, I have a button that indicates the color that the user can set to the background color of UIViewController.
My Custom Toolbar
Class for custom toolbar, ColorToolbar.swift
import UIKit
class ColorToolbar: UIToolbar {
#IBOutlet weak var purpleButton: UIBarButtonItem!
#IBOutlet weak var blueButton: UIBarButtonItem!
#IBOutlet weak var greenButton: UIBarButtonItem!
#IBOutlet weak var yellowButton: UIBarButtonItem!
#IBOutlet weak var redButton: UIBarButtonItem!
var makeNotesVC = MakeNotesVC()
var selectedColor : UIColor = UIColor.clear
override func awakeFromNib() {
super.awakeFromNib()
setupButtonColor()
}
#IBAction func colorButtonPressed(_ sender: UIBarButtonItem) {
guard let color = sender.tintColor else {return}
selectedColor = color
print(selectedColor)
makeNotesVC.view.backgroundColor = selectedColor
}
#objc func changeBgColor(){
makeNotesVC.view.backgroundColor = selectedColor
}
private func setupButtonColor(){
purpleButton.tintColor = Constants.TintColorButton.purple
blueButton.tintColor = Constants.TintColorButton.blue
greenButton.tintColor = Constants.TintColorButton.green
yellowButton.tintColor = Constants.TintColorButton.yellow
redButton.tintColor = Constants.TintColorButton.red
}
}
Class for UIViewController that i want to change background color, MakeNotesVC.swift
import UIKit
class MakeNotesVC: UIViewController {
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
#IBOutlet weak var titleTextfield: UITextField!
#IBOutlet weak var notesText: UITextView!
override func viewDidLoad() {
super.viewDidLoad()
addColorbutton()
}
#IBAction func saveButtonPressed(_ sender: UIBarButtonItem) {
let newNote = Note(context: context)
newNote.title = titleTextfield.text
newNote.text = notesText.text
self.navigationController?.popToRootViewController(animated: true)
}
func addColorbutton(){
// TODO : Add Color Options Toolbar
//Register custom toolbar
let toolbar = UINib(nibName: "Toolbar", bundle: nil).instantiate(withOwner: nil, options: nil)[0] as! ColorToolbar
toolbar.sizeToFit()
//Add toolbar to keyboard
titleTextfield.inputAccessoryView = toolbar
notesText.inputAccessoryView = toolbar
}
}
Add protocol at your custom tool bar
protocol BackgroundColorControlDelegate: AnyObject {
func changeBackgroundColor(sender:Any, color: UIColor)
}
import UIKit
class ColorToolbar: UIToolbar {
#IBOutlet weak var purpleButton: UIBarButtonItem!
#IBOutlet weak var blueButton: UIBarButtonItem!
#IBOutlet weak var greenButton: UIBarButtonItem!
#IBOutlet weak var yellowButton: UIBarButtonItem!
#IBOutlet weak var redButton: UIBarButtonItem!
var makeNotesVC = MakeNotesVC()
var selectedColor : UIColor = UIColor.clear
weak var delegate: BackgroundColorControlDelegate?
override func awakeFromNib() {
super.awakeFromNib()
setupButtonColor()
}
#IBAction func colorButtonPressed(_ sender: UIBarButtonItem) {
guard let color = sender.tintColor else {return}
selectedColor = color
print(selectedColor)
delegate?.changeBackgroundColor(sender: self, color: color)
}
#objc func changeBgColor(){
makeNotesVC.view.backgroundColor = selectedColor
}
private func setupButtonColor(){
purpleButton.tintColor = Constants.TintColorButton.purple
blueButton.tintColor = Constants.TintColorButton.blue
greenButton.tintColor = Constants.TintColorButton.green
yellowButton.tintColor = Constants.TintColorButton.yellow
redButton.tintColor = Constants.TintColorButton.red
}
}
call delegate from MakeNotesVC
import UIKit
class MakeNotesVC: UIViewController {
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
#IBOutlet weak var titleTextfield: UITextField!
#IBOutlet weak var notesText: UITextView!
override func viewDidLoad() {
super.viewDidLoad()
addColorbutton()
}
#IBAction func saveButtonPressed(_ sender: UIBarButtonItem) {
let newNote = Note(context: context)
newNote.title = titleTextfield.text
newNote.text = notesText.text
self.navigationController?.popToRootViewController(animated: true)
}
func addColorbutton(){
// TODO : Add Color Options Toolbar
//Register custom toolbar
let toolbar = UINib(nibName: "Toolbar", bundle: nil).instantiate(withOwner: nil, options: nil)[0] as! ColorToolbar
toolbar.sizeToFit()
toolbar.delegate = self
//Add toolbar to keyboard
titleTextfield.inputAccessoryView = toolbar
notesText.inputAccessoryView = toolbar
}
}
extension MakeNotesVC: BackgroundColorControlDelegate {
func changeBackgroundColor(sender:Any, color: UIColor) {
view.backgroundColor = color
}
}
I am quite new to a programming and I need a help.
I am trying to build a simple calculator. In nutshell: There are two UITextField where the numbers are inserted. There is IBAction (buttonCalculate) that performs the calculation + there is another IBAction (buttonClear) that clears the data inserted into text fields. Upon starting the application both IBAction buttons are disabled. The goal is to enable the IBAction (buttonCalculate) once numbers are inserted. In case the user inserts any other character then numbers a warning message(warrningSign2) needs to appear telling the user that ony numbers are accepted.
Can somebody give a tip / hint how I should proceed?
Thanks!
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var Value: UITextField!
#IBOutlet weak var field1: UITextField!
#IBOutlet weak var field2: UITextField!
#IBOutlet weak var buttonClear: UIButton!
#IBOutlet weak var buttonCalculate: UIButton!
#IBOutlet weak var warrningSign: UITextField!
#IBOutlet weak var warrningSign2: UITextField!
func appLoad () {
buttonClear.isEnabled = false
buttonClear.backgroundColor = .gray
if field1.text == "" || field1.text == "" {
warrningSign.textColor = .red
butonCalculate.isEnabled = false
butonCalculate.backgroundColor = .gray}
}
override func viewDidLoad() {
super.viewDidLoad()
appLoad()
}
#IBAction func calculate(_ sender: Any) {
buttonClear.isEnabled = true
buttonClear.backgroundColor = UIColor(red: 74/255, green: 105/255, blue:187/255, alpha: 1)
Value.text = String(Float(field1.text!)! + Float(field2.text!)!)
}
#IBAction func Clear(_ sender: Any) {
Value.text = "Value"
self.field1.text = nil
self.field2.text = nil
}
}
Make UITextField(field1 and field2) Keyboard type to Number Pad or only acceptable number type.
You can catch the characters sent to a UITextField control by adding the below line:
textField.addTarget(self, action: #selector(textFieldDidChange), for: .editingChanged)
In textFieldDidChange delegate method you can get the text and validate as per your needs.
I would recommend to update the code like below,
#IBAction func calculate(_ sender: Any) {
calculateAction()
}
private func calculateAction() {
buttonClear.isEnabled = true
buttonClear.backgroundColor = UIColor(red: 74/255, green: 105/255, blue:187/255, alpha: 1)
Value.text = String(Float(field1.text!)! + Float(field2.text!)!)
}
And then call the calculateAction() in textFieldDidChange().
I want to create a tab bar at the top of my page and contain only text, and when one clicked it will change the text color and underline the selected item... as shown in the image below...
I searched a lot but didn't find something to help me achieve this..
Can someone please tell me how can i do this?
Take Three Buttons and three imageviews.take action for three buttons and take outlets for images and labels as given below . use this link to easy identify.it's perfectly working for you. click here
class ViewController: UIViewController
{
#IBOutlet weak var imgDetails: UIImageView!
#IBOutlet weak var imgPassword: UIImageView!
#IBOutlet weak var imglocations: UIImageView!
#IBOutlet weak var lblDetailsTittle: UILabel!
#IBOutlet weak var lblPasswordTittle: UILabel!
#IBOutlet weak var lblLocationTittle: UILabel!
override func viewDidLoad()
{
super.viewDidLoad()
//if you want select by default Details use this code otherwise uncomment it.
imgDetails.backgroundColor = UIColor.green
imgPassword.backgroundColor = UIColor.clear
imglocations.backgroundColor = UIColor.clear
lblDetailsTittle.textColor = UIColor.black
lblPasswordTittle.textColor = UIColor.lightGray
lblLocationTittle.textColor = UIColor.lightGray
}
#IBAction func btnDetailsTouchUpInSide(_ sender: Any)
{
imgDetails.backgroundColor = UIColor.green
imgPassword.backgroundColor = UIColor.clear
imglocations.backgroundColor = UIColor.clear
lblDetailsTittle.textColor = UIColor.black
lblPasswordTittle.textColor = UIColor.lightGray
lblLocationTittle.textColor = UIColor.lightGray
}
#IBAction func btnPasswordTouchUpInSide(_ sender: Any)
{
imgPassword.backgroundColor = UIColor.green
imgDetails.backgroundColor = UIColor.clear
imglocations.backgroundColor = UIColor.clear
lblPasswordTittle.textColor = UIColor.black
lblLocationTittle.textColor = UIColor.lightGray
lblDetailsTittle.textColor = UIColor.lightGray
}
#IBAction func btnLocationsTouchUpInSide(_ sender: Any)
{
imglocations.backgroundColor = UIColor.green
imgDetails.backgroundColor = UIColor.clear
imgPassword.backgroundColor = UIColor.clear
lblLocationTittle.textColor = UIColor.black
lblPasswordTittle.textColor = UIColor.lightGray
lblDetailsTittle.textColor = UIColor.lightGray
}
}
i am doing a form using textfield and textview
after i key in all the information and click the submit button, the app will close and jump to my viewcontroller.swift and show like the below photo
and this is my viewcontroller.swift
import UIKit
import MessageUI
class ContactViewController:UIViewController,MFMailComposeViewControllerDelegate,UITextViewDelegate,UITextFieldDelegate {
#IBOutlet weak var message: UITextView!
#IBOutlet weak var contactSubject: UITextField!
#IBOutlet weak var contactNumber: UITextField!
#IBOutlet weak var contactEmail: UITextField!
#IBOutlet weak var contactName: UITextField!
#IBOutlet weak var contactDes: UILabel!
#IBOutlet weak var contactTitle: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
contactTitle.text = "SEND US A MESSAGES"
contactTitle.sizeToFit()
contactDes.text = "Do you have anything in your mind to tell us?\nPlease don’t hesitate to get in touch to us via our contact form."
contactDes.sizeToFit()
//Contact Form
contactName.delegate = self
contactEmail.delegate = self
contactNumber.delegate = self
contactSubject.delegate = self
message.delegate = self
self.message.isUserInteractionEnabled = true
self.message.isEditable = true
let borderColor : UIColor = UIColor.init(red: 46.0/255.0, green: 49.0/255.0, blue: 146.0/255.0, alpha: 1)
contactName.layer.borderWidth = 1
contactName.layer.borderColor = borderColor.cgColor
contactEmail.layer.borderWidth = 1
contactEmail.layer.borderColor = borderColor.cgColor
contactSubject.layer.borderWidth = 1
contactSubject.layer.borderColor = borderColor.cgColor
contactNumber.layer.borderWidth = 1
contactNumber.layer.borderColor = borderColor.cgColor
message.layer.borderWidth = 1
message.layer.borderColor = borderColor.cgColor
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
contactName.resignFirstResponder()
contactEmail.resignFirstResponder()
contactNumber.resignFirstResponder()
contactSubject.resignFirstResponder()
return true
}
#IBAction func submitbtn(_ sender: Any) {
let mailVC = MFMailComposeViewController()
mailVC.mailComposeDelegate = self
mailVC.setSubject(contactSubject.text!)
let email = contactEmail.text!.lowercased()
let finalemail = email.trimmingCharacters(in: NSCharacterSet.whitespacesAndNewlines)
let mailcontent = "Name :\(contactName.text!)\n\n Email:\(finalemail)\n\n Contact Numer :\(contactNumber.text!)\n\n Subject :\(contactSubject.text!)\n\n Message :\(message.text!)"
mailVC.setMessageBody(mailcontent, isHTML: false)
let toRecipent = "abc#example.com"
mailVC.setToRecipients([toRecipent])
self.present(mailVC, animated: true, completion: nil)
}
}
I have successfully got a step updating the values of a Text Field and now i am trying to add a second stepper but the app is now crashing.
#IBOutlet weak var propertyTypeField: UITextField!
#IBOutlet weak var insuranceTypeField: UITextField!
#IBOutlet weak var bedroomField: UITextField!
#IBOutlet weak var bathroomField: UITextField!
#IBOutlet weak var doYouOwnPropertyField: UITextField!
#IBOutlet weak var propertyYearField: UITextField!
#IBOutlet weak var bathroomStepper: UIStepper!
#IBOutlet weak var bedroomStepper: UIStepper!
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor(red: 0xE1/255, green: 0xE1/255, blue: 0xE1/255, alpha: 1.0)
//Bedroom stepper setup
bedroomField.text = "\(Int(bedroomStepper.value))"
bedroomStepper.addTarget(self, action: "stepperValueDidChange:", forControlEvents: .ValueChanged)
//Bathroom stepper setup
bathroomField.text = "\(Int(bathroomStepper.value))"
bathroomStepper.addTarget(self, action: "stepperValueDidChange:", forControlEvents: .ValueChanged)
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func viewTapped(sender : AnyObject) {
propertyTypeField.resignFirstResponder()
insuranceTypeField.resignFirstResponder()
bedroomField.resignFirstResponder()
bathroomField.resignFirstResponder()
doYouOwnPropertyField.resignFirstResponder()
propertyYearField.resignFirstResponder()
}
func stepperValueDidChange(stepper: UIStepper) {
let bedroomStepperMapping: [UIStepper: UITextField] = [bedroomStepper: bedroomField]
if !(bedroomField.text == ""){
bedroomStepperMapping[stepper]!.text = "\(Int(stepper.value))"}
let bathroomStepperMapping: [UIStepper: UITextField] = [bathroomStepper: bathroomField]
if !(bathroomField.text == ""){
bathroomStepperMapping[stepper]!.text = "\(Int(stepper.value))"}
}
This is the whole code i am using.
The error i am getting is
fatal error: unexpectedly found nil while unwrapping an Optional value
Hope someone can help.
Thanks
By using ! bedroomStepperMapping[stepper]!.text your telling the compiler there will be a value there. As there is not one apparently you are getting the error. Check if the value is nil before unwrapping it
To check for nil in the line you say is the issue
if !(bedroomField.text == ""){
//Ok to unwrap object
}
While if you are using the optional value first check if value exist if not then there must not b null so do it as
if let bedFeild = Int(stepper.value) {
bedroomStepperMapping[stepper].text = bedFeild
}
Now there will be no crash if the value exist then value will be assigned to it else no without any crash
func stepperValueDidChange(stepper: UIStepper) {
if bedroomStepper == stepper{
bedroomField.text = "\(Int(stepper.value))"}
if bathroomStepper == stepper{
bathroomField.text = "\(Int(stepper.value))"}
}
}