import UIKit
class ExpandableTextFieldViewController: UIViewController, UITextViewDelegate {
// Create a UITextView
let textView: UITextView = {
let textView = UITextView()
textView.translatesAutoresizingMaskIntoConstraints = false
textView.isScrollEnabled = false // Disable scrolling
textView.font = UIFont.systemFont(ofSize: 16) // Set your preferred font size
textView.layer.borderColor = UIColor.gray.cgColor
textView.layer.borderWidth = 1.0
textView.layer.cornerRadius = 5.0
textView.textContainerInset = UIEdgeInsets(top: 8, left: 8, bottom: 8, right: 8) // Adjust padding
return textView
}()
override func viewDidLoad() {
super.viewDidLoad()
// Add the UITextView to the view
view.addSubview(textView)
// Set delegates
textView.delegate = self
// Add constraints
NSLayoutConstraint.activate([
textView.topAnchor.constraint(equalTo: view.topAnchor, constant: 20),
textView.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 20),
textView.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -20),
textView.bottomAnchor.constraint(lessThanOrEqualTo: view.bottomAnchor, constant: -20), // Ensure it doesn't go beyond the bottom of the screen
// Set an initial height constraint (you can change this to your preferred initial height)
textView.heightAnchor.constraint(equalToConstant: 100).withPriority(.defaultLow) // Set content hugging priority to low
])
// Customize placeholder text and color
textView.text = "Enter text here"
textView.textColor = UIColor.lightGray
}
// MARK: - UITextViewDelegate methods
func textViewDidChange(_ textView: UITextView) {
// Adjust the height of the UITextView based on its content
let fixedWidth = textView.frame.size.width
let newSize = textView.sizeThatFits(CGSize(width: fixedWidth, height: .greatestFiniteMagnitude))
textView.heightAnchor.constraint(equalToConstant: newSize.height).isActive = true
}
func textViewDidBeginEditing(_ textView: UITextView) {
// Remove placeholder text when the user starts editing
if textView.textColor == UIColor.lightGray {
textView.text = nil
textView.textColor = UIColor.black
}
}
func textViewDidEndEditing(_ textView: UITextView) {
// Add placeholder text if the user ends editing with an empty field
if textView.text.isEmpty {
textView.text = "Enter text here"
textView.textColor = UIColor.lightGray
}
}
}
2条答案
按热度按时间c3frrgcw1#
您不能扩展xmlextFiled的高度。
但是你可以使用ExtView来实现,你要做的是
使用extextView代替extFiled,并将ScrollEnabled设置为false,给予extView top、bottom、leading和trailing约束。
给予高度约束给extView,并将其内容优先级设置为低。
现在你的文本视图将根据插入的文本展开。
是的,您必须手动添加和管理占位符逻辑
nue99wik2#
下面是以编程方式创建多行扩展UTextField的完整工作代码: