帶Placeholder的UITextView(轉自StackOverflow)

kim_jin發表於2017-12-13

CustomTextView.h

#import <UIKit/UIKit.h>

@interface SJTextView : UITextView

/// Placeholder
@property (nonatomic, copy) NSString *placeholder;

@end
複製程式碼

CustomTextView.m

#import "SJTextView.h"

@interface SJTextView ()
/// Label that show placeholder
@property (nonatomic, strong) UILabel *placeholderLabel;
@end


@implementation SJTextView

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
		[[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(textChanged:)
                                                     name:UITextViewTextDidChangeNotification
                                                   object:nil];
    }
    return self;
}

- (void)awakeFromNib {
    [super awakeFromNib];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(textChanged:)
                                                 name:UITextViewTextDidChangeNotification
                                               object:nil];
}

- (void)drawRect:(CGRect)rect {
    [super drawRect:rect];
    if (self.placeholder.length > 0) {
        if (!self.placeholderLabel) {
            self.placeholderLabel = [[UILabel alloc] initWithFrame: CGRectMake(8, 8, self.bounds.size.width - 16, 0)];
            self.placeholderLabel.numberOfLines = 0;
            self.placeholderLabel.font = self.font;
            self.placeholderLabel.textColor = [UIColor lightGrayColor];
            self.placeholderLabel.lineBreakMode = NSLineBreakByWordWrapping;
            self.placeholderLabel.alpha = 0;
            self.placeholderLabel.tag = 999;
            [self addSubview:self.placeholderLabel];
        }

        self.placeholderLabel.text = self.placeholder;
        [self.placeholderLabel sizeToFit];
    }

    if (self.text.length == 0 && self.placeholder.length > 0) {
        [self viewWithTag:999].alpha = 1;
    }
}

- (void)textChanged:(NSNotification *)aNotification {
    if (self.placeholder.length == 0) return;
    [UIView animateWithDuration:0.25 animations:^{
        if (self.text.length == 0) {
            self.placeholderLabel.alpha = 1;
        } else {
            self.placeholderLabel.alpha = 0;
        }
    }];
}

- (void)setText:(NSString *)text {
    [super setText:text];
    [self textChanged:nil];
}
複製程式碼

原文地址:

Placeholder in UITextView

相關文章