Secure text .echosbullets not working for password field - swift

Here's what I've got:
#IBOutlet weak var password: NSSecureTextField!
#IBOutlet weak var shwpswd: NSButton! //Checkbox
#IBOutlet weak var pswdcell: NSSecureTextFieldCell! //Cell
#IBAction func shwpswd(_ sender: Any) {
if(shwpswd.state == 1) {
pswdcell.echosBullets = false // Turn the Secure text into regular text
}
else if(shwpswd.state == 0) {
pswdcell.echosBullets = true // Secure text
}
}
Everything seems to run fine, except the text in the password field doesn't change states between echoing bullets and echoing the real text. Everything is linked together properly too - Cell is within the text field, password button is in the view and the outlet works. I'm wondering if this is another one of the "Swift on mac < Swift on iOS cases".
EDIT: Here is the final solution, should anyone care to see it:
#IBOutlet weak var shwpswd: NSButton! //Checkbox
#IBOutlet weak var visPswd: NSTextfield! //hidden regular box to show chars
#IBOutlet weak var password: NSSecureTextField! //visible initial secure box
#IBAction func shwpswd(_ sender: Any) {
if(shwpswd.state == 1) {
self.visPswd.stringValue = self.password.stringValue //Sync both the text fields
self.password.isHidden = true //hide the secure field
self.visPswd.isHidden = false //show the real character echo field
}
else if(shwpswd.state == 0) {
self.password.stringValue = self.visPswd.stringValue //Sync the two
self.password.isHidden = false // Inverse of above
self.visPswd.isHidden = true
}
}
Note the text fields password and visPswd are the same size and position in the view - one remains hidden at all times to avoid overlapping. When the user enters values in either the password or visPswd field, it syncs with the other field when the checkbox state is changed.

You can accomplish what you want adding a second text field in top of your secure field. Add an IBAction to your check box to switch your fields isHidden property and copy the other textField stringValue and make it the first responder. Your implementation should look like something like this:
import Cocoa
class ViewController: NSViewController {
#IBOutlet weak var password: NSSecureTextField!
#IBOutlet weak var showPassword: NSTextField!
#IBOutlet weak var shwpswd: NSButton!
override func viewDidLoad() {
super.viewDidLoad()
shwpswd.state = .off
showPassword.isHidden = true
}
override func viewDidAppear() {
super.viewDidAppear()
password.window?.makeFirstResponder(password)
}
#IBAction func showHidePassword(_ sender: NSButton) {
showPassword.isHidden.toggle()
password.isHidden.toggle()
if !showPassword.isHidden {
showPassword.stringValue = password.stringValue
showPassword.becomeFirstResponder()
} else {
password.stringValue = showPassword.stringValue
password.becomeFirstResponder()
}
}
}
show/hide password sample

Related

macOS Swift TextField.stringValue not returning updated value until I click on something else

I apologize if this has been asked before but I couldn't find what I was looking for online over the last few hours. I'm still functional a noob with swift.
I am trying to store the stringValue of a TextField when I click a NSButton. If I click anywhere and then click on the NSButton the code works perfect but if I don't click the stringValue is still reporting the previous value.
#IBOutlet weak var NameText: NSTextField!
#IBOutlet weak var SaveChangesAccountButton: NSButton!
var selectedAccountItemNumber = NSInteger()
#IBAction func SaveAccountChanges(_ sender: Any)
{
let AccountName = NameText.stringValue
AccountingData.instance.book.account[selectedAccountItemNumber].name = AccountName
}
You have to call validateEditing() on the text field.
And please conform to the naming convention that variable and function names start with a lowercase letter and don't use NSInteger in Swift.
#IBOutlet weak var nameText: NSTextField!
#IBOutlet weak var saveChangesAccountButton: NSButton!
var selectedAccountItemNumber = 0
#IBAction func saveAccountChanges(_ sender: Any)
{
nameText.validateEditing()
let accountName = nameText.stringValue
AccountingData.instance.book.account[selectedAccountItemNumber].name = accountName
}

switching image on timed event in swift

I am trying to switch the displayed image in an UIImageView to different images based on an timed event by defining the what image should be displayed by I and the app works but when the timer gets to 5 the app crashes. if anyone can help me out then that would be great (also the Ad is the beginning of the image name so AD_1 - AD_4)
import UIKit
class ViewController: UIViewController {
//this is for declaring all the profile buttons
#IBOutlet weak var Icon_1: UIButton!
#IBOutlet weak var Icon_2: UIButton!
#IBOutlet weak var Icon_3: UIButton!
#IBOutlet weak var Icon_4: UIButton!
#IBOutlet weak var Icon_5: UIButton!
#IBOutlet weak var Icon_6: UIButton!
#IBOutlet weak var Icon_7: UIButton!
#IBOutlet weak var Icon_8: UIButton!
//this is used to swich the images
var i = Int(1)
let timer = Timer.scheduledTimer(timeInterval: 5.0, target: self, selector: #selector(fire), userInfo: nil, repeats: false)
//this is for the view
#IBOutlet weak var ad_view: UIView!
//this is for when the user swipes left
#IBAction func Icon_Swipe_Left(_ sender: Any) {
Icon_1.isHidden = true
Icon_2.isHidden = true
Icon_3.isHidden = true
Icon_4.isHidden = true
Icon_5.isHidden = false
Icon_6.isHidden = false
Icon_7.isHidden = false
Icon_8.isHidden = false
}
//this is when the user swipes right
#IBAction func Icon_Swipe_Right(_ sender: Any) {
Icon_1.isHidden = false
Icon_2.isHidden = false
Icon_3.isHidden = false
Icon_4.isHidden = false
Icon_5.isHidden = true
Icon_6.isHidden = true
Icon_7.isHidden = true
Icon_8.isHidden = true
}
// this is for decareing the image frame for the adds
#IBOutlet weak var Ad_Frame: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
//this is for showing the fist set of icons
Icon_1.isHidden = false
Icon_2.isHidden = false
Icon_3.isHidden = false
Icon_4.isHidden = false
//this is for hideing the second set of icons
Icon_5.isHidden = true
Icon_6.isHidden = true
Icon_7.isHidden = true
Icon_8.isHidden = true
self.Ad_Frame.image = UIImage(named: "AD_\(i)")
}
#objc func fire()
{
i += 1
self.Ad_Frame.image = UIImage(named: "AD_\(i)")
}
}
Two things:
1: you say you have images AD_1 - AD_4 - that's only four images, so it won't cope with the fifth! I'm assuming you mean AD_1 - AD_5
2: More importantly, you start with i = 1, and then add 1 before trying to display the image, so you're actually trying to display images 2...6.
Increment i after displaying the image, not before
Change fire so that it starts over once 5 is reached
#objc func fire() {
self.Ad_Frame.image = UIImage(named: "AD_\(i)")
i += 1
if i > 4 { i = 1 }
}
Off-topic but I would recommend renaming i to something more readable like counter for instance. Single letter variables are not recommended apart from in for loops. Also when declaring it you don't need to call Int(...) but assign the value directly instead, var counter = 1

How do I check if x is in a variable in classes within a list?

I have a list called mainframe which holds classes. I want to check before adding a new username; if newusername is in mainframe.usernames perform adding the new username in.
pretty much something like this:
import UIKit
class addNewPassword: UIViewController {
var homeVC = Home()
#IBOutlet weak var createHolderItem: UITextField!
#IBOutlet weak var createHolderUsername: UITextField!
#IBOutlet weak var createHolderPassword: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
}
#IBAction func savePasswordButton(_ sender: Any) {
let holder = Holder()
holder.item = createHolderItem.text!
holder.username = createHolderUsername.text!
holder.password = createHolderPassword.text!
}
if mainframe.contains(where: { $0.username == holder.username }) {
print("test")
}
else {
homeVC.mainframe.append(holder)
homeVC.tableView.reloadData()
navigationController?.popViewController(animated: true)
}
}
I pretty much want to run a loop, within an if statement. Or am I approaching it the wrong way?
I'm new to programming, did online tutorials and trying to write my first iOS app for my aunt.
if mainframe.usernames.contains(holder.username) {
...
Use contains :
if mainframe.usernames.contains(holder.username) {
...
}

if statement returning a value not working for UiLabel

my fairly new to swift and programming, I'm trying to display a value from an if statement. Here is my func within my UiLabel. I've tried a few variations along the same lines but it only every returns "calculate.fuelTank" it never seems to trigger the second part to my IF statement?
#IBOutlet weak var startingFuelDisplay: UILabel! //not working yet
func refreshUiopeningFuel() {
if calculate.totalFuel <= Double(calculate.fuelTank) {
print (Double(calculate.fuelTank)) // FuelTank
} else {
print (calculate.totalFuel) // TotalFuel
}
Do I need to add a bool argument to trigger "else"? I have also tried using the "return" function with initialised string which included the value I was trying to extract, finally I need this to work for another display.
here is my full view controller code (i'm new I'm sure it could be cleaner)
import UIKit
class ViewController: UIViewController {
let calculate = Inputs ( raceLaps: 13, fuelRate: 3.7, fuelTank: 110, laptime: 85.456, tyreWear: 0.05 )
#IBOutlet weak var rate: UITextField!
#IBOutlet weak var laps: UITextField!
#IBOutlet weak var tank: UITextField!
#IBOutlet weak var tyreWear: UITextField!
#IBOutlet weak var laptime: UITextField!
#IBOutlet var cancelKeyboard: UITapGestureRecognizer!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
//Looks for single or multiple taps.
let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: "dismissKeyboard")
view.addGestureRecognizer(tap)
}
//Calls this function when the tap is recognized.
func dismissKeyboard() {
//Causes the view (or one of its embedded text fields) to resign the first responder status.
view.endEditing(true)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
refreshUiFuel()
refreshUiStops()
refreshUiTyreLife()
refreshUiTyreLifeLaps()
refreshUiopeningFuel()
refreshUiBoxOnLap ()
}
#IBAction func calculate(sender: UIButton) {
if let rateVal = Double(rate.text!),
tankVal = Int(tank.text!),
lapVal = Int(laps.text!),
wearVal = Double(tyreWear.text!),
laptimeVal: Float = 85.456 {
let fuelModel = Inputs(raceLaps: lapVal, fuelRate: rateVal, fuelTank: tankVal, laptime: laptimeVal, tyreWear: wearVal )
totalFuelDisplay.text = ("\(Double(fuelModel.totalFuel))")
totalStopsDisplay.text = ("\(Int(fuelModel.totalStops))")
tyreLifeDisplay.text = ("\(Int(fuelModel.tyreChangesRaceDistanceTotal))")
tyreLifeLapsDisplay.text = ("\(Int(fuelModel.tyreLife))")
startingFuelDisplay.text = ("\(refreshUiopeningFuel())")
}
else {
totalFuelDisplay.text = "missing value"
totalStopsDisplay.text = "missing value"
tyreLifeDisplay.text = "missing value"
tyreLifeLapsDisplay.text = "missing value"
startingFuelDisplay.text = "missing Value"
}
}
#IBOutlet weak var totalFuelDisplay: UILabel!
func refreshUiFuel()->String {
return totalFuelDisplay.text!
}
#IBOutlet weak var totalStopsDisplay: UILabel!
func refreshUiStops()->String {
return totalStopsDisplay.text!
}
#IBOutlet weak var tyreLifeDisplay: UILabel!
func refreshUiTyreLife()->String {
return tyreLifeDisplay.text!
}
#IBOutlet weak var tyreLifeLapsDisplay: UILabel!
func refreshUiTyreLifeLaps()->String {
return tyreLifeLapsDisplay.text!
}
#IBOutlet weak var pitOnLapDisplay: UILabel!
func refreshUiBoxOnLap () {
}
#IBOutlet weak var startingFuelDisplay: UILabel! //not working yet
func refreshUiopeningFuel() ->Double {
print(calculate.fuelTank)
print(calculate.totalFuel)
if calculate.totalFuel <= Double(calculate.fuelTank) {
return Double(calculate.fuelTank) // FuelTank
} else {
return calculate.totalFuel // TotalFuel
}
}
}
all helped welcomed
Judging from the natural real-world logic, it appears you've simply reversed the if/else logic. It would seem that if totalFuel is less than the tank's capacity (the if clause), you should return totalFuel in that case, and return the tank capacity in the else clause.

Textfield and floats in Swift

I have 2 textfields. If they both has a float value bigger than 100, when you click on my button it should allow you to go to another page.
So far so good, however in my code the text field can't have either int or float or doubles...
What can I do?
As Lukas says you need to convert it to a string. If you are capturing the value in the textfield on button click, you need to convert it, like so:
if let doubleValue = Double(textField.text!) {
}
I think based on what you have said, you need to do something like this:
class ViewController: UIViewController {
#IBOutlet weak var box1: UITextField!
#IBOutlet weak var box2: UITextField!
#IBOutlet weak var Check: UIButton!
#IBOutlet weak var Page1: UILabel!
#IBAction func didPressCheckButton(sender: UIButton) {
if let stringValue = box1.text {
if let doubleValue = Double(stringValue) {
if doubleValue > 100 {
print("Navigate to next page")
}
}
}
}
}
You will need to modify the check so that you check if both text boxes have values over 100, but this is a starting point.