67 lines
1.9 KiB
Swift
67 lines
1.9 KiB
Swift
//
|
|
// PlaceholderTextView.swift
|
|
// Tusker
|
|
//
|
|
// Created by Shadowfacts on 8/29/18.
|
|
// Copyright © 2018 Shadowfacts. All rights reserved.
|
|
//
|
|
|
|
import UIKit
|
|
|
|
// Source: https://finnwea.com/blog/adding-placeholders-to-uitextviews-in-swift/
|
|
extension UITextView: UITextViewDelegate {
|
|
|
|
override open var bounds: CGRect {
|
|
didSet {
|
|
resizePlaceholder()
|
|
}
|
|
}
|
|
|
|
var placeholder: String? {
|
|
get {
|
|
return (viewWithTag(100) as? UILabel)?.text
|
|
}
|
|
set {
|
|
if let placeholderLabel = viewWithTag(100) as? UILabel {
|
|
placeholderLabel.text = newValue
|
|
placeholderLabel.sizeToFit()
|
|
} else {
|
|
guard let newValue = newValue else { return }
|
|
addPlaceholder(newValue)
|
|
}
|
|
}
|
|
}
|
|
|
|
public func textViewDidChange(_ textView: UITextView) {
|
|
if let placeholderLabel = viewWithTag(100) as? UILabel {
|
|
placeholderLabel.isHidden = !text.isEmpty
|
|
}
|
|
}
|
|
|
|
private func resizePlaceholder() {
|
|
guard let placeholderLabel = viewWithTag(100) as? UILabel else { fatalError() }
|
|
let labelX = textContainer.lineFragmentPadding
|
|
let labelY = textContainerInset.top
|
|
let labelWidth = frame.width - (labelX * 2)
|
|
let labelHeight = placeholderLabel.frame.height
|
|
placeholderLabel.frame = CGRect(x: labelX, y: labelY, width: labelWidth, height: labelHeight)
|
|
}
|
|
|
|
private func addPlaceholder(_ placeholderText: String) {
|
|
let placeholderLabel = UILabel()
|
|
|
|
placeholderLabel.text = placeholderText
|
|
placeholderLabel.sizeToFit()
|
|
placeholderLabel.font = font
|
|
placeholderLabel.textColor = .lightGray
|
|
placeholderLabel.tag = 100
|
|
|
|
placeholderLabel.isHighlighted = !text.isEmpty
|
|
|
|
addSubview(placeholderLabel)
|
|
resizePlaceholder()
|
|
delegate = self
|
|
|
|
}
|
|
}
|