iOS Revisited: Text Field

Hot

Post Top Ad

Showing posts with label Text Field. Show all posts
Showing posts with label Text Field. Show all posts

13 Nov 2017

Limit characters in TextField or TextView Swift

11/13/2017 08:33:00 am 0
In this article we will learn how to set maximum character length to a UITextField and UITextView.

We go through each one separately.

UITextField:

First add UITextField to the view and conform to UITextFieldDelegate.

Next add the following delegate method for setting up the maximum limit:

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    let currentText = textField.text ?? ""
    guard let stringRange = Range(range, in: currentText) else { return false }
    let updatedText = currentText.replacingCharacters(in: stringRange, with: string)
    return updatedText.count <= 10 // Change limit based on your requirement.
} 

Above example is for, if user asked to enter his/her mobile number, assume maximum length as 10.

Download the sample project from the bottom of this article.

UITextView:

Add UITextView to the view and conform to UITextViewDelegate.

Next add the following delegate method for setting the maximum limit:

func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
    let currentText = textView.text ?? ""
    guard let stringRange = Range(range, in: currentText) else { return false }
    let updatedText = currentText.replacingCharacters(in: stringRange, with: text)
    return updatedText.count <= 50 // Change limit based on your requirement.
}

Above example is for, if user asked to enter about his/her, assume maximum limit here 50 characters.

Download sample project with example :

Read More

30 Oct 2017

Add Placeholder To UITextView in Swift 4 - iOS

10/30/2017 11:21:00 am 0
Swift provides default placeholder property to UITextField but not to UITextView.

So if you need a multi-line editable text view, you don’t get a pretty placeholder. Here you will learn how to add placeholder text to UItextView.


Here we will show step by step:

Step 1:

Firstly create new swift file and name it TextViewPlaceholder.swift and save it.

Next import UIKit and create extension to UITextView as follow:

import UIKit

extension UITextView: UITextViewDelegate {
// Code
}

Step 2:

Here we are going to add label as subview in order to show placeholder text. No worries it's quite simple.

Add the following code inside the extension:

override open var bounds: CGRect {
    didSet {
        self.resizePlaceholder()
    }
}

public var placeholder: String? {
    get {
        var placeholderText: String?
        
        if let placeholderLbl = self.viewWithTag(50) as? UILabel {
            placeholderText = placeholderLbl.text
        }
        
        return placeholderText
    }
    set {
        if let placeholderLbl = self.viewWithTag(50) as! UILabel? {
            placeholderLbl.text = newValue
            placeholderLbl.sizeToFit()
        } else {
            self.addPlaceholder(newValue!)
        }
    }
}

public func textViewDidChange(_ textView: UITextView) {
    if let placeholderLbl = self.viewWithTag(50) as? UILabel {
        placeholderLbl.isHidden = self.text.characters.count > 0
    }
}

private func resizePlaceholder() {
    if let placeholderLbl = self.viewWithTag(50) as! UILabel? {
        let x = self.textContainer.lineFragmentPadding
        let y = self.textContainerInset.top - 2
        let width = self.frame.width - (x * 2)
        let height = placeholderLbl.frame.height
        
        placeholderLbl.frame = CGRect(x: x, y: y, width: width, height: height)
    }
}

private func addPlaceholder(_ placeholderText: String) {
    let placeholderLbl = UILabel()
    
    placeholderLbl.text = placeholderText
    placeholderLbl.sizeToFit()
    
    placeholderLbl.font = self.font
    placeholderLbl.textColor = UIColor.lightGray
    placeholderLbl.tag = 50
    
    placeholderLbl.isHidden = self.text.characters.count > 0
    
    self.addSubview(placeholderLbl)
    self.resizePlaceholder()
    self.delegate = self
}

Above code will work in both orientations.

Step 3:

Here we will show how to use.

Simply add placeholder to UITextView as below:

let textView = UITextView()
textView.placeholder = "Start typing here"


Get the full code here.

Read More

17 Oct 2017

How to add TextField to Alert View in swift 4?

10/17/2017 03:19:00 am 0
Adding UITextField to alertview became easy from swift 3 by using UIAlertController.

Here we will show step by step.

How to add UITextField to Alert View in swift 4?

Step 1:

First create UIAlertController object with title and message as follow:

let alertVC = UIAlertController(title: "Enter credentials", message: "Provide Email & Password", preferredStyle: .alert)

Step 2:

Next add UITextField's to alertVC using addTextField() method as follow:

alertVC.addTextField { (textField) in
    textField.placeholder = "Email"
}
alertVC.addTextField { (textField) in
    textField.placeholder = "Password"
    textField.isSecureTextEntry = true
}

Step 3:

Then add the UIAlertAction with title and completion handler as follow:

let submitAction = UIAlertAction(title: "Submit", style: .default, handler: {
    (alert) -> Void in
    
    let emailTextField = alertVC.textFields![0] as UITextField
    let passwordTextField = alertVC.textFields![1] as UITextField
    
    print("Email -- \(emailTextField.text!), Password -- \(passwordTextField.text!)")
})

Step 4:

Finally add the UIAlertAction to alertVC and present alertVC as follow:

alertVC.addAction(submitAction)
alertVC.view.tintColor = UIColor.black
present(alertVC, animated: true)

The final output will looks like following image:

uialertcontroller with textfield swift 4

Read More

Post Top Ad