Swift 4 iOS - Word Count from UITextField - ios

Trying to make a "word count" feature using Swift 4 iOS - UITextField. The following code is unable to print the .count for strings typed inside my UITextField.
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
//INPUT BOX - for Word Count!
let INPUT : UITextField = UITextField(frame: CGRect(x: 35, y: 200, width: 350, height:50))
INPUT.placeholder = "Type Words separated with Spaces!"
INPUT.font = UIFont.init(name:"times", size: 22)
INPUT.backgroundColor = UIColor(red:0x00 ,green:0xff, blue:0x00 ,alpha:1)
self.view.addSubview(INPUT)
//variable holding the value of text typed
let strings : String! = INPUT.text
//variable holding the methods for detecting spaces and new lines
let spaces = CharacterSet.whitespacesAndNewlines.union(.punctuationCharacters)
//variable storing the amount of words minus the spaces
let words = strings.components(separatedBy: spaces)
//method to display the word count in the console
print(words.count)
}
}
This error is being printed in the console:
"Result" => : 0

That's because your textview has no text in it at that point.
Try this:
INPUT.text = "Some Text"
Do get the text from an actual input:
INPUT.addTarget(self, action: #selector(textFieldDidChange(_:)), for: .editingChanged)
func textFieldDidChange(_ textField: UITextField) {
let strings : String! = INPUT.text
let spaces = CharacterSet.whitespacesAndNewlines.union(.punctuationCharacters)
let words = strings.components(separatedBy: spaces)
print(words.count)
}

Related

How to show pyramid pattern on UILabel on Button Click(swift language)

///swift iOS
/// I have tried with below code
#IBOutlet weak var myLbl: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
}
func magic(choose: String, row: Int) -> String {
var name = ""
for i in 1...row {
name += (String.init(repeating: " ", count: row-i)+String.init(repeating: choose, count: 2*i-1))
}
return name
}
#IBAction func btnPressed(_ sender: UIButton) {
let result = magic(choose: "0", row: 5)
myLbl.text = result
}
plz check images which type of response I am getting
}[I am getting output at this manner][1]
[1]: https://i.stack.imgur.com/YdV8f.png
we have to show this type of response on my UILabel
Please open up a fresh playground and paste the following code in:
import UIKit
let label = UILabel()
label.text = " 0 \n000" // simple demo text
label.numberOfLines = 0 // unlimited number of lines
label.font = .monospacedSystemFont(ofSize: 14, weight: .regular) // monospaced font so that columns are aligned
label.sizeToFit() // tell the label to evaluate its content and adjust its size to fit
It should display a basic example of what you want and give you all the information you need to update your code accordingly.

Add inputAccessoryToolbar [duplicate]

Fairly new to iOS development so forgive me for asking something that might be quite obvious. As you all know the UITextField's keyboard with keyboardType set to .NumberPad looks like the following...
.NumberPad keyboard
What I would like to do is replace the empty space in the lower left corner with a minus sign. Is this possible or does one need to write an entire custom keyboard to achieve this?
Would really appreciate the help.
Add a toolbar to your textfield inputAccessoryView and when the textfield will become the responder then the keyboard will show the toolbar (Swift 3.0):
func addToolBar(){
let toolbar = UIToolbar(frame: CGRect(x: 0, y: 0, width: self.view.bounds.size.width, height: 44))
let minusButton = UIBarButtonItem(title: "-", style: .plain, target: self, action: #selector(toggleMinus))
toolbar.items = [minusButton]
theTextField.inputAccessoryView = toolbar
}
func toggleMinus(){
// Get text from text field
if var text = theTextField.text , text.isEmpty == false{
// Toggle
if text.hasPrefix("-") {
text = text.replacingOccurrences(of: "-", with: "")
}
else
{
text = "-\(text)"
}
// Set text in text field
theTextField.text = text
}
}
hope it helps.
Swift 5.2
Set up the UIToolbar as described above and then use an extension on UITextField:
import UIKit
extension UITextField {
func toggleMinus() {
guard let text = self.text, !text.isEmpty else { return }
self.text = String(text.hasPrefix("-") ? text.dropFirst() : "-\(text)")
}
}
Usage:
#objc func toggleMinus() {
yourTextField.toggleMinus()
}

How to create an array of UITextField objects in Swift?

I am working on an application in Swift. At the beginning I provide number of inputs that I would like to add. In next view I create as many UITextFields as I defined in first view.I have a problem with storing of all this values from TextFields after pressing the button. It seems to me that the most effective solution is to create an array of UITextFields and add every value of TextField into array and then in action for button adding values which are in all TextFields into array. Unfortunately, it doesn't work. Any suggestions? Thanks in advance.
override func viewDidLoad() {
super.viewDidLoad()
var counter = 0
for i in 1...mainInstance.numberOfInputs
{
super.viewDidLoad()
array.insert(UITextField(frame: CGRect(x: 0, y: 50, width: 60, height: 20)), at: i)
array[i].center = CGPoint(x: 200,y: 50 + counter)
array[i].textAlignment = NSTextAlignment.center
array[i].layer.borderWidth = 1
array[i].layer.borderColor = UIColor.black.cgColor
self.outletScrollView.addSubview(array[i])
counter += 50
}
super.viewDidLoad()
let button = UIButton(type: .system) // let preferred over var here
button.frame = CGRect(x: 200, y: 50 + counter, width: 100, height: 20)
button.setTitle("Recalculate", for: UIControlState.normal)
button.addTarget(self, action: "actionRecalculate:", for: UIControlEvents.touchUpInside)
self.outletScrollView.addSubview(button)
outletScrollView.contentInset = UIEdgeInsetsMake(0, 0, CGFloat(counter+100), 0)
}
You could create easily with:
let textFields = [UITextField]()
You should consider using an UIScrollView, (like in your example) or (better idea in my opinon) a UITableView to add your UITextfields. So you have multiple Rows, and every row has one UITextField. The number of rows / Textfield can u easily customize (and get it from your FirstViewController for example).
Just create a custom UITableViewCell - add an UITextField and connect the IBOutlet. To get the values from every UITextField you could iterate through all cells, and read out the values. Just ask, if you need more help about doing that.
Creating array of UITextfield could be done this way
// Create an empty array of type UITextField
var listOfTextFields : [UITextField] = []
// In viewDidLoad, create a textfield and add it to the array
override func viewDidLoad() {
super.viewDidLoad()
for i in 0...mainInstance.numberOfInputs-1 {
let textField = UITextField((frame: CGRect(x: X, y: Y*i, width: yourWidth, height: yourHeight)))
textField.delegate = self
listOfTextFields.append(textField)
}
}
In this UITextField setup, I didn't account for any formatting to shorten the answer.
Though this might not be for the exact use case, it could help others with similar use cases (particularly programmatically created textfields or custom uicell).
txtfield.tag = indexPath.row // or other int
Then you implement textfield didEndEditing after array has been initialized and delegating
#IBAction func endedEditing(_ sender: UITextField) {
arr[sender.tag] = sender.text
}

Adding a minus sign to the UITextField's .NumberPad keyboard

Fairly new to iOS development so forgive me for asking something that might be quite obvious. As you all know the UITextField's keyboard with keyboardType set to .NumberPad looks like the following...
.NumberPad keyboard
What I would like to do is replace the empty space in the lower left corner with a minus sign. Is this possible or does one need to write an entire custom keyboard to achieve this?
Would really appreciate the help.
Add a toolbar to your textfield inputAccessoryView and when the textfield will become the responder then the keyboard will show the toolbar (Swift 3.0):
func addToolBar(){
let toolbar = UIToolbar(frame: CGRect(x: 0, y: 0, width: self.view.bounds.size.width, height: 44))
let minusButton = UIBarButtonItem(title: "-", style: .plain, target: self, action: #selector(toggleMinus))
toolbar.items = [minusButton]
theTextField.inputAccessoryView = toolbar
}
func toggleMinus(){
// Get text from text field
if var text = theTextField.text , text.isEmpty == false{
// Toggle
if text.hasPrefix("-") {
text = text.replacingOccurrences(of: "-", with: "")
}
else
{
text = "-\(text)"
}
// Set text in text field
theTextField.text = text
}
}
hope it helps.
Swift 5.2
Set up the UIToolbar as described above and then use an extension on UITextField:
import UIKit
extension UITextField {
func toggleMinus() {
guard let text = self.text, !text.isEmpty else { return }
self.text = String(text.hasPrefix("-") ? text.dropFirst() : "-\(text)")
}
}
Usage:
#objc func toggleMinus() {
yourTextField.toggleMinus()
}

How can I make UILabel or UIButton with two lines , the first with one character and the second with two characters?

I want a UILabel or UIButton with two lines , the first with one character and the second with two characters as the image below
Does anyone have any idea?
For multiline UIButton just set Line Break to Word Wrap and set your buttons text with the new line character (in interface builder it is ctrl+enter).
override func viewDidLoad() {
super.viewDidLoad()
let myText = "3\npm"
myLabel.numberOfLines = 0
myLabel.text = myText
}
I am assuming that you have "3 pm" string,
first split the string into an array
var str = "3 pm"
var strArr = split(str) {$0 == " "}
var str1: String = strArr[0]
var str2: String = strArr[1]
label.lineBreakMode = NSLineBreakMode.ByWordWrapping
label.numberOfLines = 2
label.text = str1+"\n"+str2
But make sure that you have set the height of label properly to show the 2 lines.

Resources