Created
October 20, 2021 08:25
-
-
Save jeandavid/1d70bdb64ee403fcb96788ed86f3b18e to your computer and use it in GitHub Desktop.
UITextView Placeholder support
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import UIKit | |
// https://stackoverflow.com/a/50671026 | |
extension UITextView { | |
private class PlaceholderLabel: UILabel { } | |
private var placeholderLabel: PlaceholderLabel { | |
guard let label = subviews.first(where: { $0 is PlaceholderLabel }) as? PlaceholderLabel else { | |
let label = PlaceholderLabel(frame: .zero) | |
label.font = font | |
label.textColor = .placeholderText | |
addSubview(label) | |
return label | |
} | |
return label | |
} | |
@IBInspectable | |
var placeholder: String { | |
get { | |
return placeholderLabel.text ?? "" | |
} | |
set { | |
let placeholderLabel = self.placeholderLabel | |
placeholderLabel.text = newValue | |
placeholderLabel.numberOfLines = 0 | |
let width = frame.width - textContainer.lineFragmentPadding * 2 | |
let size = placeholderLabel.sizeThatFits(CGSize(width: width, height: .greatestFiniteMagnitude)) | |
placeholderLabel.frame.size.height = size.height | |
placeholderLabel.frame.size.width = width | |
placeholderLabel.frame.origin = CGPoint(x: textContainer.lineFragmentPadding + textContainerInset.left, y: textContainerInset.top) | |
textStorage.delegate = self | |
} | |
} | |
} | |
extension UITextView: NSTextStorageDelegate { | |
public func textStorage(_ textStorage: NSTextStorage, didProcessEditing editedMask: NSTextStorage.EditActions, range editedRange: NSRange, changeInLength delta: Int) { | |
if editedMask.contains(.editedCharacters) { | |
placeholderLabel.isHidden = !text.isEmpty | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment