帶占位文字的TextView

作為輸入框UITextFieldUITextView各有優缺點,開發中經常需要使用到這兩個輸入框,UITextField可以通過placeholder這個屬性來加入占位文字,但不能換行;UITextView雖然能自動換行,卻沒有placeholder這種方便的方式添加占位文字,雖然可以通過attributeString來設置,但還是覺得不是特別方便。
最好的方法就是自定義一個UITextView的子類PlaceholderView,那么這個類里面的任何內容都是你說了算,為UITextView添加placeholder功能只需要簡單的兩個步驟:一個通知和一個重寫drawRect方法。

在初始化時添加通知

- (instancetype)initWithFrame:(CGRect)frame textContainer:(NSTextContainer *)textContainer {

    self = [super initWithFrame:frame textContainer:textContainer];
    if (self) {
        [self registerNotification];
    }
    return self;
}

- (void)registerNotification {
    [self unregisterNotification];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textDidChange) name:UITextViewTextDidChangeNotification object:nil];

}

通知方法里面告訴UITextView需要重繪

- (void)textDidChange {
    [self setNeedsDisplay];
}

重繪視圖

- (void)drawRect:(CGRect)rect {
    if ([self hasText]) {
        return;
    }

    // 設置字體屬性

    NSMutableDictionary *attrs = [NSMutableDictionary dictionaryWithCapacity:0];

    attrs[NSFontAttributeName] = self.font;

    attrs[NSForegroundColorAttributeName] = self.placeholderColor;

    rect.origin.x = 5;
    rect.origin.y = 7;
    rect.size.width -= 2 * rect.origin.x;
    rect.size.height -= 2 * rect.origin.y;
    [self.placeholder drawInRect:rect withAttributes:attrs];
}

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容