При разработке приложений для iOS UITextView — это часто используемый компонент для отображения и редактирования многострочного текста. Однако, в отличие от UITextField, UITextView не имеет встроенного текстового свойства-заполнителя. В этой статье мы рассмотрим различные методы установки текста-заполнителя в UITextView с использованием Swift 5, а также примеры кода.
Метод 1: наложение UILabel
Один из подходов к отображению текста-заполнителя в UITextView — наложение UILabel поверх него. Вот пример фрагмента кода, демонстрирующий этот метод:
import UIKit
class ViewController: UIViewController, UITextViewDelegate {
let textView = UITextView()
override func viewDidLoad() {
super.viewDidLoad()
setupTextView()
}
func setupTextView() {
textView.frame = CGRect(x: 20, y: 100, width: 200, height: 100)
textView.delegate = self
textView.font = UIFont.systemFont(ofSize: 16)
textView.layer.borderWidth = 1
textView.layer.borderColor = UIColor.lightGray.cgColor
view.addSubview(textView)
let placeholderLabel = UILabel()
placeholderLabel.text = "Enter text here..."
placeholderLabel.font = UIFont.italicSystemFont(ofSize: textView.font?.pointSize ?? 16)
placeholderLabel.sizeToFit()
textView.addSubview(placeholderLabel)
textView.setValue(placeholderLabel, forKey: "_placeholderLabel")
}
func textViewDidChange(_ textView: UITextView) {
let placeholderLabel = textView.value(forKey: "_placeholderLabel") as? UILabel
placeholderLabel?.isHidden = !textView.text.isEmpty
}
}
Метод 2: расширение UITextView
Другой способ установить текст-заполнитель — создать расширение для UITextView. Это позволяет использовать более многоразовый и краткий подход. Вот пример реализации этого метода:
import UIKit
extension UITextView {
func setPlaceholder(text: String) {
let placeholderLabel = UILabel()
placeholderLabel.text = text
placeholderLabel.font = self.font
placeholderLabel.sizeToFit()
placeholderLabel.textColor = UIColor.lightGray
placeholderLabel.tag = 999
placeholderLabel.isHidden = !self.text.isEmpty
self.addSubview(placeholderLabel)
self.delegate = self
}
}
class ViewController: UIViewController, UITextViewDelegate {
let textView = UITextView()
override func viewDidLoad() {
super.viewDidLoad()
setupTextView()
}
func setupTextView() {
textView.frame = CGRect(x: 20, y: 100, width: 200, height: 100)
textView.font = UIFont.systemFont(ofSize: 16)
textView.layer.borderWidth = 1
textView.layer.borderColor = UIColor.lightGray.cgColor
view.addSubview(textView)
textView.setPlaceholder(text: "Enter text here...")
}
func textViewDidChange(_ textView: UITextView) {
let placeholderLabel = textView.viewWithTag(999) as? UILabel
placeholderLabel?.isHidden = !textView.text.isEmpty
}
}
Метод 3: NSAttributedString
Третий подход предполагает использование NSAttributedString для установки текста-заполнителя в UITextView. Этот метод обеспечивает большую гибкость в настройке внешнего вида текста-заполнителя. Вот пример:
import UIKit
class ViewController: UIViewController, UITextViewDelegate {
let textView = UITextView()
let placeholderText = "Enter text here..."
override func viewDidLoad() {
super.viewDidLoad()
setupTextView()
}
func setupTextView() {
textView.frame = CGRect(x: 20, y: 100, width: 200, height: 100)
textView.delegate = self
textView.font = UIFont.systemFont(ofSize: 16)
textView.layer.borderWidth = 1
textView.layer.borderColor = UIColor.lightGray.cgColor
view.addSubview(textView)
let attributes: [NSAttributedString.Key: Any] = [
.foregroundColor: UIColor.lightGray,
.font: UIFont.italicSystemFont(ofSize: textView.font?.pointSize ?? 16)
]
textView.attributedPlaceholder = NSAttributedString(string: placeholderText, attributes: attributes)
}
func textViewDidChange(_ textView: UITextView) {
// Placeholder text is handled automatically by using attributedPlaceholder.
// No additional code is needed for this method.
}
}
В этой статье мы рассмотрели три различных метода установки текста-заполнителя в UITextView с помощью Swift 5. Накладывая UILabel, создавая расширение UITextView или используя NSAttributedString, вы можете добиться желаемого поведения. Выберите метод, который лучше всего соответствует вашим требованиям, и улучшите взаимодействие с пользователем в приложениях iOS.
Реализуя эти методы, вы можете легко добавлять текст-заполнитель к компонентам UITextView в ваших проектах Swift 5, улучшая пользовательский интерфейс и взаимодействие.