Skip to content

Instantly share code, notes, and snippets.

@vikaskore
Last active July 8, 2023 09:03
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vikaskore/5d5973f748235b8c04fee46cbacdc4cd to your computer and use it in GitHub Desktop.
Save vikaskore/5d5973f748235b8c04fee46cbacdc4cd to your computer and use it in GitHub Desktop.
Set placeholder text to TextView in iOS Swift 4
//
// DemoViewController.swift
// Samples
//
// Created by VikasK on 27/02/19.
// Copyright © 2019 Vikaskore Software. All rights reserved.
import UIKit
class DemoViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UITextFieldDelegate, UITextViewDelegate {
@IBOutlet var contactTableView: UITableView!
var placeholder = "Please comment here..."
override func viewDidLoad() {
super.viewDidLoad()
//.lightGray : placeholder text color
//.black : text color
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "TxtViewTableViewCell") as! TxtViewTableViewCell
cell.txtView.text = placeholder
if placeholder == "Please comment here..." {
cell.txtView.textColor = .lightGray
} else {
cell.txtView.textColor = .black
}
return cell
}
//MARK:- TextView Delegates
func textViewDidBeginEditing(_ textView: UITextView) {
if textView.textColor == .lightGray {
textView.text = nil
textView.textColor = .black
}
}
func textViewDidEndEditing(_ textView: UITextView) {
if textView.text.isEmpty {
textView.text = "Please comment here..."
textView.textColor = UIColor.lightGray
placeholder = ""
} else {
placeholder = textView.text
}
}
func textViewDidChange(_ textView: UITextView) {
placeholder = textView.text
}
/*
To print remaining allowed characters(Suppose you have 20 character limit)
countingLabel is to display number of remaining character user can enter in textView, like: 10/20, 9/20
*/
@IBOutlet var countingLabel: UILabel!
func textViewDidChange(_ textView: UITextView) {
countingLabel.text = "\(20 - textView.text.count)/20"
}
func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
return textView.text.count + (text.count - range.length) <= 20
}
//MARK:- Button Action
func sendButtonTapped() {
self.view.endEditing(true)
//send logic goes here
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment