[iOS 개발팁] UITextView에 placeholder 추가하기

텍스트 입력할 수 있는 UITextView, UITextField를 사용하다보면, "제목을 입력해주세요", "내용을 입력해주세요" 등의 placeholder 값을 넣을 경우가 많습니다.

기본적으로 UITextField에서는 placeholder 프로퍼티를 제공하지만, UITextView에서는 placeholder 제공하지 않지 않습니다.

내용과 같은 많은 텍스트를 입력해야하는 경우에는 UITextViewDelegate를 사용하여, 텍스트를 입력받기전, 입력받은 후에 "내용을 입력해주세요" 텍스트를 넣어주었다가, 지워주어야합니다.

굉장히 불편한데요, UITextView를 상속받아 클래스를 만들고, placeholder 와 같은 기능을 구현하여 이용하면 편리합니다.

먼저, UITextView를 상속받은 클래스는 만들고, PlaceholderTextView.h placeholder 변수를 생성합니다.

=============================================================================
#import <UIKit/UIKit.h>

@interface PlaceholderTextView : UITextView


@property (strong, nonatomic) NSString *placeholder;


@end
=============================================================================

PlaceholderTextView.m 구현부의 
drawRect 함수에서 UILabel를 만들어서 UITextView 위에 Add해줍니다.
그리고 UITextView의 값을 변경할때 함수로 호출할수 있도록 노티피케이션으로 등록합니다.


=============================================================================
- (void)drawRect:(CGRect)rect
{
    if(self.placeholder.length > 0) {
        if(self.placeholderLabel == nil) {
            
            float linePadding = self.textContainer.lineFragmentPadding;
            CGRect placeholderRect = CGRectMake(self.textContainerInset.left + linePadding,
                                                self.textContainerInset.top,
                                                rect.size.width - self.textContainerInset.left - self.textContainerInset.right - 2 * linePadding,
                                                rect.size.height - self.textContainerInset.top - self.textContainerInset.bottom);
            self.placeholderLabel = [[UILabel alloc]initWithFrame:placeholderRect];
            self.placeholderLabel.font = self.font;
            self.placeholderLabel.textAlignment = self.textAlignment;
            self.placeholderLabel.textColor = UICOLOR_181;
            [self addSubview:self.placeholderLabel];
            
            self.placeholderLabel.text = self.placeholder;
            [self.placeholderLabel sizeToFit];
         
             [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textChanged:) name:UITextViewTextDidChangeNotification object:nil];
        }
        [self showOrHidePlaceholder];
    }
    
    [super drawRect:rect];
}

=============================================================================

textChanged()함수에서는 UITextView에서 키보드 입력이 발생했을때 showOrHidePlaceholder() 함수를 호출하도록 구현합니다.

=============================================================================
- (
void)textChanged:(NSNotification *)notification
{
    if(self.placeholder.length == 0)
        return;
    
    [UIView animateWithDuration:0.1 animations:^{
        [self showOrHidePlaceholder];
    }];
}
=============================================================================

showOrHidePlaceholder()함수에서는 입력한 텍스트의 길이가 0보다 클때 UITextView 위에 추가한 placeholerLabel를 알파값을 조정하여 감춥니다. 그러면, 사용자가 입력한 텍스트가 한자라도 있을 경우 placeholerLabel 안보일꺼고, 사용자가 입력한 텍스트가 없을 경우 다시 placeholerLabel이 노출됩니다.

=============================================================================
- (void)showOrHidePlaceholder
{
    if(self.text.length == 0)
        [self.placeholderLabel setAlpha:1.0];
    else
        [self.placeholderLabel setAlpha:0];
}
=============================================================================

댓글

주간 인기글

카드뉴스 마케팅 팁

[ubuntu] 신규 계정에 sudo 권한 추가하기

SPA(Sigle Page Applications) 란 무엇인가?

[Vue] 전화번호 입력/조회시 '-' 자동으로 넣어주기

[MySQL] DB Time Zone 변경