deleteCharactersInRange:NSMakeRange equivalent in swift 3 to delete characters one by one from last index of string - swift

I have user input string which contains characters. I want to delete those characters one by one from its last index when I tap button until the string is empty
Here is my string variable
#IBAction func btnBackSpaceAction(_ sender: AnyObject) {
if self.userInput.characters.count >= 1{
let string = String(self.userInput.characters.dropLast())
print(string)
}
}
How to delete characters from last?

You can try something like this
var string = "Good Morning" // Your string
#IBAction func bnuttonAction(_ sender: UIButton) { //Your button action
string = String(string.characters.dropLast())
if !string.isEmpty {
print(string)
}
else {
print("String is Empty")
}
}
Output:
Good Mornin
Good Morni
Good Morn
Good Mor
Good Mo
Good M
...

Related

How to Pass the data given in UITextField to another variable on another class

So i have a UITextField named apiTextField and a function of the saveButton :
func saveButton(_ sender: Any) {
}
I want when the user writes to the UITextField and press the saveButton that text the user wrote be passed to a variable which is called var baseURL:String? in another class.
I didn't find anything related to UITextField so i decided to make this question, another similar one is 10 years old!.
var anotherClass = AnotherClass()
func saveButton(_ sender: Any) {
guard let text = apiTextField.text, !text.isEmpty else { return }
anotherClass.baseURL = text
}
Is that what you are looking for?

Trying to make a backspace button programmatically to do the same as the keyboard delete (ᗏX) button

#objc func searchButtonTap() {
searchBar.becomeFirstResponder()
var remove = searchBar.text
remove = String(remove!.dropLast())
searchBar.text = remove
}
Also tried two backspaces
#objc func searchButtonTap() {
let name: String = searchBar.text!
let endIndex = name.index(name.endIndex, offsetBy: -2)
let truncated = String(name[..<endIndex])
searchBar.text = truncated
}
Assuming that you want to remove the last character of the search bar text when the user taps on back(search?) button.
So,
#objc func searchButtonTap() {
guard !(searchBar.text?.isEmpty ?? true) else { return } //Making sure that you don't hit the "Fatal error: Can't remove more items from a collection than it contains"
searchBar.text?.removeLast(1)
}

How to delete a character from a UI Label in Swift?

I am new to Swift and I am having issues with deleting a character from a UI Label that I have created. I am trying to make a simple phone dailer app, and I am trying ti implement a backspace button. My UI Label is called DailerLabel, and I know I'm supposed to use the dropLast() function but I keep running into issues about mismatching types or unwrappers. I am not really sure what I am supposed to do here. I tried the thing in the commented code which didn't work, and then I tried what I listed below which doesn't either. Could anyone help me?
#IBAction func backspaceButtonPressed(_ sender: UIButton) {
if (!((DailerLabel.text?.isEmpty)!)) {
// DailerLabel.text?.substring(to: (DailerLabel.text?.index(before: (DailerLabel.text?.endIndex)!))!)
let temp = DailerLabel.text
temp?.dropLast()
DailerLabel.text = temp
}
You can try this one, replace label with your own UILabel
var name: String = label.text! //shauket , for example
name.remove(at: name.index(before: name.endIndex))
print(name) //shauke
label.text = name
print(label.text!)
You are very close. dropLast actually returns the string without the last character and you haven't stored that to anything so there is no change. You also have to conver back to String from Substring.
#IBAction func backspaceButtonPressed(_ sender: UIButton) {
if (!((DailerLabel.text?.isEmpty)!)) {
let temp = DailerLabel.text ?? ""
DailerLabel.text = String(temp.dropLast())
}
}
Here's a better version
#IBAction func backspaceButtonPressed(_ sender: UIButton) {
guard
let text = dialerLabel.text,
!text.isEmpty
else {
return
}
dialerLabel.text = String(text.dropLast())
}

Swift: Add comma and $ in the textfield when typing

I want the users see the $ and comma when they are typing in a textfield from numberPad (Without a decimal dot). Previously I got help and use below codes. But clients will not type the decimal (Only Int value).
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
let oldText = textField.text! as NSString
var newText = oldText.stringByReplacingCharactersInRange(range, withString: string) as NSString!
var newTextString = String(newText)
let digits = NSCharacterSet.decimalDigitCharacterSet()
var digitText = ""
for c in newTextString.unicodeScalars {
if digits.longCharacterIsMember(c.value) {
digitText.append(c)
}
}
let formatter = NSNumberFormatter()
// formatter.usesSignificantDigits = false
formatter.numberStyle = NSNumberFormatterStyle.CurrencyStyle
formatter.locale = NSLocale(localeIdentifier: "en_US")
let numberFromField = (NSString(string: digitText).doubleValue) / 100
newText = formatter.stringFromNumber(numberFromField)
textField.text = String(newText)
return false
}
When typing, it always starts from the second decimal unit, How to remove the ".00" via editing the code and let it start from the unit? I tried for a long time, thanks in advance.
First, you got some bad advice. You should not be using shouldChangeCharactersInRange to change the characters in a text field. That's for checking if the characters typed are valid for the field. The only thing you should do in this method is return true if the user entered digits or delete, otherwise false. (Remember, the user may be using an external keyboard so just having the keypad up isn't good enough to stop non-digit entry.)
Instead you should be using an #IBAction connected to the field's EditingChanged event. Inside this method is where you should update the text.
#IBAction func editingChanged(sender: UITextField) {
let digits = sender.text?.digitsOnly ?? "0"
sender.text = "$\(digits).00" // If I understand what you want.
}
The below extension should be somewhere in your code base. It's generally useful so store it in a gist or something, you will likely need it in future projects.
extension String {
var digitsOnly: String {
return componentsSeparatedByCharactersInSet(NSCharacterSet.decimalDigitCharacterSet().invertedSet).joinWithSeparator("")
}
}
You have to make sure that the IBAction is attached to the EditingChanged event:
For Swift 4x
extension String {
var digitsOnly: String {
return components(separatedBy: NSCharacterSet.decimalDigits.inverted).joined(separator: "")
}
}

Force patterns in textfields

(Swift)
So the problem is:
My app (which is a kind of calculator) is crashing when the user puts in the textfield things that can't be calculated.
For example, if he types " -4-.", the app won't be able to do the math.
So, a pattern must be followed.
The following characters are allowed: 1234567890.-
The minus sign can only be typed when it is the first character in the textfield and cannot be typed again.
The point can only be typed after a number, and cannot be typed again.
Well you would have to determine:
When the user clicks on a number/digit/character, you would have to do a:
//Goes at top of one of your classes
var decimalCount:Int = 0
//At location of tap for character
if(decimalCount < 1) {
textField.text += "."
decimalCount += 1
}
This ideology could be applied to "-" as well.
Some how i have understood your question. According to my assumption our task is to validate the input for proper math function.Ok here we go.
First of all declare a bool variable at top of your class
var isNonNumericCharactersAllowes = true
At first we need to make our textfield to respond according to user input.So add delegate to text field and add the following delegate method.
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
//1. To make sure that this is applicable to only particular textfield add tag.
if textField.tag == 1 {
let char = string.cStringUsingEncoding(NSUTF8StringEncoding)!
let isBackSpace = strcmp(char, "\\b")
//Helps to react only while typing and not while clearing text
if (isBackSpace != -92) {
let numbersOnly = NSCharacterSet(charactersInString: "1234567890")
let characterSetFromTextField = NSCharacterSet(charactersInString: string)
let Validate:Bool = numbersOnly .isSupersetOfSet(characterSetFromTextField)
if !Validate {
if isNonNumericCharactersAllowes {
isNonNumericCharactersAllowes = false
return true
}
return false
}
isNonNumericCharactersAllowes = true
}
}
return true
}
The above method stops unusual text entry's such as 0..012,--4,4++ etc..
Now while hitting calculate button we need to some validation.Add the following code in IBAction.
#IBAction func calculate(sender: AnyObject) {
let textContent:String!
textContent = textFieldTwo.text
var characterContainer = textContent.characters.map { String($0) }
let numbersOnly = NSCharacterSet(charactersInString: "1234567890")
let lastObjectOfString = NSCharacterSet(charactersInString: characterContainer.last!)
let Validate:Bool = numbersOnly .isSupersetOfSet(lastObjectOfString)
if !Validate {
characterContainer .removeLast()
textFieldTwo.text = characterContainer .joinWithSeparator("")
}
}
This above validation helps in removing things like 30+20+,4+4+, etc.. i.e removes unused operators at the end.