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().
Related
I want to set a custom font to UIButton. I need to set it programmatically because the font is not applied otherwise. The problem is that it changes back to the built-in font after the click. What am I doing wrong?
import UIKit
class LoginViewController: UIViewController {
#IBOutlet weak var emailTextField: UITextField!
#IBOutlet weak var passwordTextField: UITextField!
#IBOutlet weak var eyeButton: UIButton!
#IBOutlet weak var loginButton: UIButton!
var iconClick = true
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
}
override func viewDidLoad() {
super.viewDidLoad()
loginButton.titleLabel?.font = UIFont(name: "Capitana-Bold", size: CGFloat(16))
}
#IBAction func iconAction(sender: AnyObject) {
if (iconClick == true) {
passwordTextField.isSecureTextEntry = false
eyeButton.setImage(UIImage(named: "eye-closed"), for: .normal)
} else {
passwordTextField.isSecureTextEntry = true
eyeButton.setImage(UIImage(named: "eye-open"), for: .normal)
}
iconClick = !iconClick
}
#IBAction func onLoginClicked(_ sender: Any) {
}
}
In iOS 15 you need to use configuration for button. This should work:
loginButton.configuration?.attributedTitle?.font = UIFont(name: "Capitana-Bold", size: CGFloat(16))
This is an iOS 15 Filled button. You cannot configure it by saying
loginButton.titleLabel?.font = ...
That was possible (but wrong) in iOS 14 and before, but with an iOS 15 button it is impossible. To configure a Filled button programmatically, you must set its configuration object.
https://developer.apple.com/documentation/uikit/uibutton/configuration
In particular you want to set the button configuration attributed title.
https://developer.apple.com/documentation/uikit/uibutton/configuration/3750779-attributedtitle
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.
I have a formulary of login, with 3 fields and a button to login. I wants set a button in the keyboard do jump of UITextField to next when user ends write the content. Besides that, when user put text on last field, the button login is hidden behind keyboard! I tried choose the options on the attributes inspector, but I don't know how use this.
class ViewControllerAuthentication: UIViewController {
#IBOutlet weak var btEntrar: UIButton!
#IBOutlet weak var textPassword: UITextField!
#IBOutlet weak var textEmail: UITextField!
#IBOutlet weak var textURL: UITextField!
let alert = Alerta()
var url : String?
var email : String?
var password : String?
override func viewDidLoad() {
self.btEntrar.addTarget(self, action: #selector(clickEntrar), for: .touchUpInside)
}
#objc func clickEntrar(_ sender : UIButton) {
// Do anything
}
}
You can do it, using UITextFieldDelegate, like...
class ViewControllerAuthentication: UIViewController, UITextFieldDelegate {
#IBOutlet weak var textPassword: UITextField!
#IBOutlet weak var textEmail: UITextField!
#IBOutlet weak var textURL: UITextField!
override func viewDidLoad() {
textPassword.delegate = self
textEmail.delegate = self
textURL.delegate = self
textURL.returnKeyType = .next
textEmail.returnKeyType = .next
textPassword.returnKeyType = .default // or .done
}
public func textFieldShouldReturn(_ textField: UITextField) -> Bool {
switch textField {
case textURL:
textEmail.becomeFirstResponder()
case textEmail:
textPassword.becomeFirstResponder()
case textPassword:
textField.resignFirstResponder()
default:
textField.resignFirstResponder()
}
return true
}
}
I suggest IQKeyboardManager, if you don't want to handle each field manually.
I want to change uilabel value and show uiview that has hide like a popup windows.
When I touch a button, that code print "setPopupView 0".
but doesn't show settingView.
and I touch a button again.
print "setPopupView 0" and show settingView.
so When "settingLabelValueUnit text" has changed not show settingView,
but when "settingLabelValueUnit text" has not changed show settingView.
(It means "settingLabelValue text" is same as input value)
I don't know why.
Anyone can help me?
Thank you
here is my swift code.
class ViewController: UIViewController {
#IBOutlet weak var workoutScrollView: UIScrollView!
#IBOutlet weak var settingView: UIView!
#IBOutlet weak var settingLabelValueUnit: UILabel!
#IBOutlet weak var imgSettingBGcal: UIImageView!
#IBOutlet weak var imgSettingBGdis: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
self.imgSettingBGcal.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(calSettingClick)))
self.imgSettingBGdis.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(disSettingClick)))
}
func calSettingClick(sender: UITapGestureRecognizer) {
setPopupView(0)
}
func disSettingClick(sender: UITapGestureRecognizer) {
setPopupView(1)
}
func showPopup (_ settype:Int) {
switch settype {
case 0:
print("setPopupView 0")
self.settingLabelValueUnit.text = "Set1"
self.workoutScrollView.isHidden = true
self.settingView.isHidden = false
case 1:
print("setPopupView 0")
self.settingLabelValueUnit.text = "Set2"
self.workoutScrollView.isHidden = true
self.settingView.isHidden = false
}
}
}
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))"}
}
}