我的应用程序使用UITextView。现在我想让UITextView有一个占位符,类似于你可以为UITextField设置的占位符。
如何做到这一点?
我的应用程序使用UITextView。现在我想让UITextView有一个占位符,类似于你可以为UITextField设置的占位符。
如何做到这一点?
当前回答
你可以在UITextView上设置标签
[UITextView addSubView:lblPlaceHoldaer];
并隐藏在TextViewdidChange方法上。
这是一个简单易行的方法。
其他回答
我找到了一个很容易模仿占位符的方法
在NIB或代码设置你的textView的textColor为lightGrayColor(大多数时候) 确保你的textView的委托链接到文件的所有者和实现UITextViewDelegate在你的头文件 将文本视图的默认文本设置为(例如:"Foobar placeholder") 实现:(BOOL) textViewShouldBeginEditing:(UITextView *)textView
编辑:
Changed if statements to compare tags rather than text. If the user deleted their text it was possible to also accidentally delete a portion of the place holder @"Foobar placeholder".This meant if the user re-entered the textView the following delegate method, -(BOOL) textViewShouldBeginEditing:(UITextView *) textView, it would not work as expected. I tried comparing by the color of the text in the if statement but found that light grey color set in interface builder is not the same as light grey color set in code with [UIColor lightGreyColor]
- (BOOL) textViewShouldBeginEditing:(UITextView *)textView
{
if(textView.tag == 0) {
textView.text = @"";
textView.textColor = [UIColor blackColor];
textView.tag = 1;
}
return YES;
}
当键盘返回并且[textView length] == 0时,也可以重置占位符文本
编辑:
只是为了让最后一部分更清楚——下面是如何将占位符文本设置回去:
- (void)textViewDidChange:(UITextView *)textView
{
if([textView.text length] == 0)
{
textView.text = @"Foobar placeholder";
textView.textColor = [UIColor lightGrayColor];
textView.tag = 0;
}
}
你也可以创建一个新的类TextViewWithPlaceholder作为UITextView的子类。
(这段代码有点粗糙——但我认为它在正确的轨道上。)
@interface TextViewWithPlaceholder : UITextView
{
NSString *placeholderText; // make a property
UIColor *placeholderColor; // make a property
UIColor *normalTextColor; // cache text color here whenever you switch to the placeholderColor
}
- (void) setTextColor: (UIColor*) color
{
normalTextColor = color;
[super setTextColor: color];
}
- (void) updateForTextChange
{
if ([self.text length] == 0)
{
normalTextColor = self.textColor;
self.textColor = placeholderColor;
self.text = placeholderText;
}
else
{
self.textColor = normalTextColor;
}
}
在委托中,添加以下内容:
- (void)textViewDidChange:(UITextView *)textView
{
if ([textView respondsToSelector: @selector(updateForTextChange)])
{
[textView updateForTextChange];
}
}
在看完所有答案后,我意识到我需要一些简单的,同时可重用的东西,这样我就可以在我的项目中为所有uitextview添加相同的功能。最后我得到了以下代码:
extension UITextView {
// MARK: TextView PlaceHolderLabel Setup
func createPlaceHolderLabel(with text: String) {
let lbl = UILabel()
self.addSubview(lbl)
// Add your constraints here
lbl.text = text
lbl.textColor = .lightGray
}
// My Textview contains only one UILabel, and for my use case the below code works, tweak it according to your use case
// Lastly two methods to toggle between show and hide the placeholder label
func hidePlaceHolderLabel() {
guard let lbl = self.subviews.first(where: { $0 is UILabel }) else { return }
lbl.isHidden = true
}
func showPlaceHolderLabel() {
guard let lbl = self.subviews.first(where: { $0 is UILabel }) else { return }
lbl.isHidden = false
}
}
当UILabel作为子视图添加到UITextView时,textView游标位置和UILabel位置将不匹配,因此在占位符文本之前留下一个空间
class ViewController: UIViewController, UITextViewDelegate {
var textView: UITextView!
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(textView)
// Also setup textView constraints as per your need
// Add placeholder to your textView
// Leave one space before placeholder string
textView.createPlaceHolderLabel(with: " Address")
textView.delegate = self
}
然后在textViewdidChange方法中添加以下代码
func textViewDidChange(_ textView: UITextView) {
if textView.text.isEmpty {
textView.showPlaceHolderLabel()
} else {
textView.hidePlaceHolderLabel()
}
}
它可以在所有uitextview中重用。
在swift 5。工作很好。
class BaseTextView: UITextView {
// MARK: - Views
private var placeholderLabel: UIlabel!
// MARK: - Init
override init(frame: CGRect, textContainer: NSTextContainer?) {
super.init(frame: frame, textContainer: textContainer)
setupUI()
startupSetup()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setupUI()
startupSetup()
}
deinit {
NotificationCenter.default.removeObserver(self)
}
}
// MARK: - Setup UI
private extension BaseTextView {
func setupUI() {
addPlaceholderLabel()
textColor = .textColor
}
func addPlaceholderLabel() {
placeholderLabel = BaseLabel(frame: .zero)
placeholderLabel.translatesAutoresizingMaskIntoConstraints = false
insertSubview(placeholderLabel, at: 0)
placeholderLabel.alpha = 0
placeholderLabel.numberOfLines = 0
placeholderLabel.backgroundColor = .clear
placeholderLabel.textColor = .lightTextColor
placeholderLabel.lineBreakMode = .byWordWrapping
placeholderLabel.isUserInteractionEnabled = false
placeholderLabel.font = UIFont.openSansSemibold.withSize(12)
placeholderLabel.topAnchor.constraint(equalTo: topAnchor, constant: 8).isActive = true
placeholderLabel.leftAnchor.constraint(equalTo: leftAnchor, constant: 5).isActive = true
placeholderLabel.rightAnchor.constraint(lessThanOrEqualTo: rightAnchor, constant: -8).isActive = true
placeholderLabel.bottomAnchor.constraint(lessThanOrEqualTo: bottomAnchor, constant: -8).isActive = true
}
}
// MARK: - Startup
private extension BaseTextView {
func startupSetup() {
addObservers()
textChanged(nil)
font = UIFont.openSansSemibold.withSize(12)
}
func addObservers() {
NotificationCenter.default.addObserver(self, selector: #selector(textChanged(_:)), name: UITextView.textDidChangeNotification, object: nil)
}
}
// MARK: - Actions
private extension BaseTextView {
@objc func textChanged(_ sender: Notification?) {
UIView.animate(withDuration: 0.2) {
self.placeholderLabel.alpha = self.text.count == 0 ? 1 : 0
}
}
}
// MARK: - Public methods
extension BaseTextView {
public func setPlaceholder(_ placeholder: String) {
placeholderLabel.text = placeholder
}
}
你可以在textview上设置一个标签。
MyUITextView.h
@interface MyUITextView : UITextView {
UILabel* _placeholderLabel;
}
@property(nonatomic, assign)NSString *placeholder;
MyUITextView.m
@implementation MyUITextView
- (id)initWithFrame:(CGRect)frame {
if (self = [super initWithFrame:frame]) {
// Create placeholder
viewFrame = CGRectMake(0, 0, frame.size.width, 15);
_placeholderLabel = [[UILabel alloc] initWithFrame:viewFrame];
_placeholderLabel.textColor = [UIColor lightGrayColor];
[self addSubview:_placeholderLabel];
// Add text changed notification
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textChanged:) name:UITextViewTextDidChangeNotification object:nil];
}
return self;
}
- (void)setPlaceholder:(NSString *)placeholder {
_placeholderLabel.text = placeholder;
}
- (NSString*)placeholder {
return _placeholderLabel.text;
}
#pragma mark UITextViewTextDidChangeNotification
- (void)textChanged:(NSNotification *)notification {
_placeholderLabel.hidden = ([self.text lenght] == 0);
}
@end