Swift3: Live UiLabel update on user input
Use the delegate method:
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
label.text = textField.text
return true
}
Why my label left 1 character when updating UILabel from UITextField?
textField:shouldChangeCharactersIn:range:replacementString
is called before the change is applied to the text field, this allows your app to veto the request and filter out unwanted content.
The problem is, you're relying on the text field's text. Instead, you need build the resulting value from the information passed to the delegate and apply that
Maybe something more like...
extension CreateEventVC: UITextFieldDelegate {
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
let text = textField.text ?? ""
eventNameLabel.text = (text as NSString).replacingCharacters(in: range, with: string)
return true;
}
}
Assign action to UITextField and update UILabel
Assumptions:
- Your text field is named
textField
- Your label is named
label
You can check it in that button action function like following:
if let text = textField.text {
if text == "Specified Text" {
label.text = "Correct"
}
}
So if textField's text is equal to your specified text label's text will be "Correct", otherwise nothing will happen.
If by virtual send button you mean the return button of keyboard, you need to do the following in textFieldShouldReturn
delegate method:
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
if let text = textField.text {
if text == "Specified text" {
label.text = "Correct"
}
textField.text = ""
}
textField.resignFirstResponder() // this is optional, you might wanna hide keyboard or not
return true
}
Update label.text at runtime
If you want to know when changes are done in the textFields, func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
is not the place you want to put your calculation code.
Instead you should listen to the event .editingChanged
on text fields from your CellCustomized
class.
class RiskPlan: UIViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet weak var tableView: UITableView!
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 1
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = self.tableView!.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! CellCustomized
return cell
}
}
class CellCustomized: UITableViewCell {
@IBOutlet weak var probability: UITextField!
@IBOutlet weak var impact: UITextField!
@IBOutlet weak var riskFactor: UILabel!
var probability1 = 0
var impact1 = 0
override func awakeFromNib() {
super.awakeFromNib()
probability.addTarget(self, action: #selector(textOnTextFieldDidChange(textField:)), for: .editingChanged)
impact.addTarget(self, action: #selector(textOnTextFieldDidChange(textField:)), for: .editingChanged)
}
func textOnTextFieldDidChange(textField: UITextField) {
if textField === probability {
probability1 = Int(textField.text!) ?? 0
} else if textField === impact {
impact1 = Int(textField.text!) ?? 0
}
riskFactor.text = String(probability1 * impact1)
}
}
How do you display text from a user input? Swift 3.0
You can do this either using storyboards or programmatically. Both options works as of Xcode 8 Swift 3
Storyboards
- Drag in a
UITextField
, aUIButton
andUILabel
from the library, onto you view controller - Create an IBOutlet for the
UITextField
and theUILabel
to yourViewController.swift
file. - Then create an IBAction for the
UIButton
to the sameViewController.swift
file. Write this code in the action function for your button:
myLabel.text = myTextField.text
Your whole code should look like this:
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var myTextField: UITextField!
@IBOutlet weak var myLabel: UILabel!
@IBAction func myButtonPressed(_ sender: AnyObject) {
myLabel.text = myTextField.text
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
}
Or Programmatically:
import UIKit
class ViewController: UIViewController {
// First create your components
let myTextField: UITextField = {
let textField = UITextField()
textField.backgroundColor = .lightGray //Just so you can see it
textField.translatesAutoresizingMaskIntoConstraints = false
return textField
}()
let myLabel: UILabel = {
let label = UILabel()
label.text = "Label text" //You may want to set this to something else to start with
label.textAlignment = .center
label.translatesAutoresizingMaskIntoConstraints = false
return label
}()
let myButton: UIButton = {
let button = UIButton()
button.setTitle("Press me", for: .normal)
button.setTitleColor(UIColor.blue, for: .normal)
button.translatesAutoresizingMaskIntoConstraints = false
return button
}()
//Then add them as subViews in the viewDidLoad method and set some constraints.
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(myTextField)
myTextField.widthAnchor.constraint(equalToConstant: 250).isActive = true
myTextField.heightAnchor.constraint(equalToConstant: 50).isActive = true
NSLayoutConstraint(item: myTextField, attribute: .centerX, relatedBy: .equal, toItem: view, attribute: .centerX, multiplier: 1, constant: 0).isActive = true
NSLayoutConstraint(item: myTextField, attribute: .centerY, relatedBy: .equal, toItem: view, attribute: .centerY, multiplier: 1, constant: -100).isActive = true
view.addSubview(myLabel)
myLabel.widthAnchor.constraint(equalToConstant: 250).isActive = true
myLabel.heightAnchor.constraint(equalToConstant: 50).isActive = true
NSLayoutConstraint(item: myLabel, attribute: .centerX, relatedBy: .equal, toItem: view, attribute: .centerX, multiplier: 1, constant: 0).isActive = true
NSLayoutConstraint(item: myLabel, attribute: .centerY, relatedBy: .equal, toItem: view, attribute: .centerY, multiplier: 1, constant: 0).isActive = true
view.addSubview(myButton)
myButton.widthAnchor.constraint(equalToConstant: 250).isActive = true
myButton.heightAnchor.constraint(equalToConstant: 50).isActive = true
NSLayoutConstraint(item: myButton, attribute: .centerX, relatedBy: .equal, toItem: view, attribute: .centerX, multiplier: 1, constant: 0).isActive = true
NSLayoutConstraint(item: myButton, attribute: .top, relatedBy: .equal, toItem: myTextField, attribute: .bottom, multiplier: 1, constant: 10).isActive = true
//This sets the function for when the button is pressed
myButton.addTarget(self, action: #selector(ViewController.myButtonPressed), for: .touchUpInside)
}
//Add code here to when the button is pressed
func myButtonPressed() {
myLabel.text = myTextField.text
}
}
Is there a way to hide a UILabel when the user starts typing, and then make it re-appear if the user removes all input?
You Can do it using add a target to your textFiled with a selector like this
- add this target to ur
viewDidLoad
method
yourTextFiled.addTarget(self, action: #selector(self.textFieldDidChange(_:)), for: UIControl.Event.editingChanged)
- create selector method like this below your
viewDidLoad
Method and set if textfield.text.isEmpty than label is hidden like this
@objc func textFieldDidChange(_ textField: UITextField) {
if textField.text!.isEmpty {
label.isHidden = false
} else {
label.isHidden = true
}
}
Hope you get your desire thing !
How can I make a clickable UILabel in Swift 3?
Problem is with your Label memory allocation. You have created IBOutlet
of label but not connected it with Interface from your Storyboard/XIB view controller.
Go to your Interface Builder: (Storyboard/XIB) View Controller ▶ Select 'Connection Inspector' ▶ Connect label outlet 'back' with Label interface element
How to do a live UITextField count while typing (Swift)?
To use the function below you need to implement the UITextFieldDelegate protocol
on the text field you want to count. This gets called every time the UITextField
s text changes:
Your class declaration should look something like this
class ViewController: UIViewController, UITextFieldDelegate
You should have an @IBOutlet
similar to this
@IBOutlet var txtValue: UITextField
Set the UITextField
s delegate to self
.
override func viewDidLoad() {
super.viewDidLoad()
txtValue.delegate = self
}
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
let newLength = count(textField.text.utf16) + count(string.utf16) - range.length
mylabel.text = String(newLength) // Set value of the label
// myCounter = newLength // Optional: Save this value
// return newLength <= 25 // Optional: Set limits on input.
return true
}
Note that this function is called on all UITextField
s so if you have several UITextField
s you will need to add a logic to know witch one is calling this function.
update text field ui in swift ios
Same issue that everyone is having when wanting to do UI updates in Swift: do not ever update the UI in any secondary thread. And that means anything with closures. Since Swift is using closures so much, that issue is being seen a lot more but it isn't new.
See Swift Update Label (with HTML content) takes 1min for the correct way of doing things.
Related Topics
Uibezierpath Subclass Initializer
How Should Secure Transport Tls Be Used with Bsd Sockets in Swift
Why Swift Use a Struct as Dictionary Key Instead of a String Here
How to Catch Nsunknownkeyexception in Swift 2.2
Automatically Increase/Decrease Uilabelview Height in Uitableviewcell
How to Turn Off Core Data Write-Ahead Logging in Swift Using Options Dictionary
Why Tabbar Hides After the Segue
Error After Importing Swift into Objective-C
iOS Pass Data Back from Viewcontroller2 to Viewcontroller 1 with Presentmodalsegue
Nsclassfromstring Returning Nil for Nested Class
Routing Between Points with Mapbox
Mirror Not Working in Swift When Iterating Through Children of an Objective-C Object
How to Cluster Custom Icons Markers in Googlemaps for iOS
Your Credentials Do Not Allow Access to This Resource Twitter API Error
Nsurlsession/Nsurlconnection Http Load Failed (Kcfstreamerrordomainssl, -9802) on a Subdomain
How to Set the Size of an Uiviewrepresentable
Swift - How to Open Another Viewcontroller with Collectionviewcell Inside Uitableviewcell