簡易總結封裝一個帶有占位文字的UITextField/TextView

占位文字

  • 1、曾經有個這么一個項目需求: 使用textField時,占位文字默認是黑色的,我們的需求是當開始編輯時,讓占位文字和光標變成紅色(或其他顏色)
    • 思路: textField和button類似,內部都擁有子控件,在OC機制中,所有控件內部都是以懶加載的形式添加的.我們可以拿到textField中的子控件label,通過監聽textField的狀態,設置內部子控件label的樣式.

  • 2、當系統自帶的控件滿足不了項目要求時
    • 對于 UITextField :

    1> 有占位文字 2> 最多只能輸入一行文字

    • 對于UITextView

    1> 沒有占位文字 2> 能輸入任意行文字,并且超出顯示范圍的可以滾動(UITextView繼承自UIScrollView)

    • 而我們需要的結果 :

1> 有占位文字 2> 能輸入任意行文字
那么我們可以用腳想一想便可選擇自定義控件繼承于UITextField /UITextView,實現添加其占位文字的功能。


  • 3、以后開發中可能經常會使用到這種技術,所以我現在就總結一下如何弄占位文字以及修改占位文字的顏色,方便以后開發(只提供了一種思路,其他方法思路自己可以總結)。
    • 注意 : 以下方法我們最好是將它封裝到一個分類中,提高代碼的復用和封裝性.

以下是封裝的代碼:

一、UITextField

1.第一種方法:UITextField利用RunTime來設置占位文字的顏色

主要思路: 方法二的主要思路是利用KVC思想,拿到TextFiled內部中的子控件,在使用KVC之前,用runtime變出TextFiled中所有子控件,找到placeholderLabel即可.

########################### .h文件 ###########################
//  UITextField+LYMPlaceholderColor.m
//  Created by ming on 14/12/20.
//  Copyright ? 2014年 ming. All rights reserved.

#import <UIKit/UIKit.h>
@interface UITextField (LYMPlaceholderColor)
/** 占位顏色 */
@property (nonatomic,strong) UIColor *placeholderColor;
/** 名字 */
@property (nonatomic,copy) NSString *name;
@end

########################### .m文件 ###########################
//  UITextField+LYMPlaceholderColor.m
//  Created by ming on 14/12/20.
//  Copyright ? 2014年 ming. All rights reserved.
/**
 *  利用RunTime來設置占位文字的顏色
 */


#import "UITextField+LYMPlaceholderColor.h"
// 導入頭文件,導入下面其中一個即可
#import <objc/runtime.h>
//#import <objc/message.h>

// OC最喜歡懶加載,用的的時候才會去加載
// 需要給系統UITextField添加屬性,只能使用runtime

static NSString *const LYMPlaceholderLabelKey = @"placeholderLabel";
static NSString *const placeholderColorName = @"placeholderColor";
@implementation UITextField (LYMPlaceholderColor)

#pragma mark - 利用RunTime動態增加屬性和交換方法 =
/// 實現交換方法 (mg_setPlaceholder:和setPlaceholder:的互換)
+ (void)load{
    Method mg_setPlaceholder = class_getInstanceMethod(self, @selector(mg_setPlaceholder:));
    
    Method setPlaceholder = class_getInstanceMethod(self, @selector(setPlaceholder:));
    
    method_exchangeImplementations(setPlaceholder, mg_setPlaceholder);
}

/// 外界賦值占位顏色的時候就會調用
- (void)setPlaceholderColor:(UIColor *)placeholderColor{
    // 動態增加placeholderColor屬性
    objc_setAssociatedObject(self, (__bridge const void *)(placeholderColorName), placeholderColor, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    // 設置顏色
   UILabel *placeholderLabel = [self valueForKeyPath:LYMPlaceholderLabelKey];
    placeholderLabel.textColor = placeholderColor;
}
- (UIColor *)placeholderColor{
    //    return  _placeholderColor;
    return objc_getAssociatedObject(self,(__bridge const void *)(placeholderColorName));
}

/// 外界賦值占位文字的時候會調用(自定義的方法,用來和系統的方法交換)
- (void)mg_setPlaceholder:(NSString *)placeholder{
    // 1.設置占位文字
    [self mg_setPlaceholder:placeholder];
   
    // 2.設置占位文字顏色
    self.placeholderColor = self.placeholderColor;
}


#pragma mark - 測試RunTime動態增加屬性
- (void)setName:(NSString *)name{
    // 動態增加“name”屬性
    objc_setAssociatedObject(self, @"name", name, OBJC_ASSOCIATION_COPY_NONATOMIC);
}
- (NSString *)name{
    return objc_getAssociatedObject(self, @"name");
}

@end

總結:

1, 文本框和按鈕一樣,都可以編輯文字,所以內部是有label的,所以需要拿到文本框中的label(可以在"小面包中檢測"),當輸入文字后,有個label就會消失,那個就是占位label,所以需要拿到系統內部的私有屬性,但是不能直接拿到私有的屬性和方法,所以需要用到KVC去取值和賦值.通過"運行時"拿到屬性
2, 然后通過KVC取值
容易出錯點: 不要用setValu:forKey,程序會崩掉,要用forKeyPath:表示不管你在文件的那一層都能去拿到


2.第二種方法:UITextField 設置占位文字的顏色,讓外界直接使用(這種方法有點投機取巧)

--這樣設置相對上一中方法來說就相對比較簡潔

########################### .h文件 ###########################

#import <UIKit/UIKit.h>

@interface UITextField (placeholderColor)

/** 占位顏色 */
@property (nonatomic,strong) UIColor *placeholderColor;

@end

########################### .m文件 ###########################
/**
 *  設置占位文字的顏色,讓外界直接使用
 */

#import "UITextField+placeholderColor.h"

static NSString *const placeholderColorKey = @"placeholderLabel.textColor";

@implementation UITextField (placeholderColor)
// 重寫placeholderColor的setter方法
- (void)setPlaceholderColor:(UIColor *)placeholderColor{
    // bool屬性,有文字就這設置為YES
    BOOL change = NO;
    // 如果當前placeholder文字為空,那么就隨便賦值幾個文字,讓它不為空
    if (self.placeholder == nil) {
        self.placeholder = @"mingge";
        // 設置 change = YES
        change = YES;
    }
    [self setValue:placeholderColor forKey:placeholderColorKey];
    // 如果change = YES,那么要把placeholder文字再次設為空
    if (change) {
        self.placeholder = nil;
    }
}

// 重寫placeholderColor的getter方法
- (UIColor *)placeholderColor{
    return [self valueForKeyPath:placeholderColorKey];
}

@end

二、UITextView

1.第一種方法:UITextView利用

Quartz2D繪圖 來設置占位文字以及顏色
// 重繪
[self setNeedsDisplay];

########################### .h文件 ###########################
//  LYMTextView.h
//  Created by ming on  14/12/9.
//  Copyright ? 2014年 ming. All rights reserved.

#import <UIKit/UIKit.h>

@interface LYMTextView : UITextView
/** 占位文字 */
@property (nonatomic,copy) NSString *placeholder;
/** 文字顏色 */
@property (nonatomic,strong) UIColor *placeholderColor;
@end

########################### .m文件 ###########################
/**
 *   給UITTextView顯示占位文字的功能,以后如需使用,就可以直接拿去用
 */
#import "LYMTextView.h"

@implementation LYMTextView

#pragma mark ========== 通知 =============
- (instancetype)initWithFrame:(CGRect)frame{
    if (self = [super initWithFrame:frame]){
        self.textColor = [UIColor blackColor];
        
        // 設置占位文字的默認字體顏色和字體大小
        self.placeholderColor = [UIColor grayColor];
        self.font = [UIFont systemFontOfSize:15];
        
        // 發布通知(當空間的內容發生改變時)
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textDidChange:) name:UITextViewTextDidChangeNotification object:self];
    }
    return self;
}

- (void)textDidChange:(NSNotification *)note{
    // 重繪
    [self setNeedsDisplay];
}

// 移除監聽者
- (void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

#pragma mark ========== 繪制占位文字 ===========
// 繪制占位文字
- (void)drawRect:(CGRect)rect {
    // 如果有文字就不繪制(不執行下面的操作)
    if (self.text.length) return;
    
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
//    if (self.font) dict[NSFontAttributeName] = self.font;
//    if (self.placeholderColor)  dict[NSForegroundColorAttributeName] = self.placeholderColor;
     dict[NSFontAttributeName] = self.font;
     dict[NSForegroundColorAttributeName] = self.placeholderColor;

    
    rect.origin.x = 4;
    rect.origin.y = 8;
    rect.size.width = LYMScreenWidth - 2 * rect.origin.x;
    
    [self.placeholder drawInRect:rect withAttributes:dict];
}

#pragma mark ========== 需要重寫的屬性 ===========
// 重寫占位文字
- (void)setPlaceholder:(NSString *)placeholder{
    _placeholder = [placeholder copy];
    // 重繪
    [self setNeedsDisplay];
}

// 重寫占位文字顏色
- (void)setPlaceholderColor:(UIColor *)placeholderColor{
    _placeholderColor = placeholderColor;
    // 重繪
    [self setNeedsDisplay];
}

// 重寫占位文字字體大小
- (void)setFont:(UIFont *)font{
    [super setFont:font];
    // 重繪
    [self setNeedsDisplay];
}

// 重寫文字
- (void)setText:(NSString *)text{
    [super setText:text];
    // 重繪
    [self setNeedsDisplay];
}

// 重寫文字屬性
- (void)setAttributedText:(NSAttributedString *)attributedText{
    [super setAttributedText:attributedText];
    // 重繪
    [self setNeedsDisplay];
}

// textView的尺寸發生改變
- (void)layoutSubviews{
    [super layoutSubviews];
    // 重繪
    [self setNeedsDisplay];
}

@end

2.第二種方法:UITextView利用

刷新 來設置占位文字以及顏色
// 重新布局
[self setNeedsLayout];

########################### .h文件 ###########################
//  LYMTextViewWithLabel.h
//  Created by ming on 14/12/9.
//  Copyright ? 2014年 ming. All rights reserved.

#import <UIKit/UIKit.h>

@interface LYMTextViewWithLabel : UITextView
/** 占位文字 */
@property (nonatomic,copy) NSString *placeholder;
/** 文字顏色 */
@property (nonatomic,strong) UIColor *placeholderColor;
@end

########################### .m文件 ###########################
#import "LYMTextViewWithLabel.h"

@interface LYMTextViewWithLabel ()
/** 占位Label */
@property (nonatomic,weak)  UILabel *placeholderLabel;
@end

@implementation LYMTextViewWithLabel

#pragma mark ========== 通知 =============
- (instancetype)initWithFrame:(CGRect)frame{
    if (self = [super initWithFrame:frame]){
        // 創建一個UILabel
        UILabel *placeholderLabel = [[UILabel alloc] init];
        placeholderLabel.numberOfLines = 0;
        [self addSubview:placeholderLabel];
        self.placeholderLabel = placeholderLabel;
        
        // 設置占位文字的默認字體顏色和字體大小
        self.textColor = [UIColor blackColor];
        self.font = [UIFont systemFontOfSize:15];
        
        // 發布通知(當空間的內容發生改變時)
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textDidChange:) name:UITextViewTextDidChangeNotification object:self];
    }
    return self;
}

// 布局占位文字的位置和尺寸
- (void)layoutSubviews{
    [super layoutSubviews];
    self.placeholderLabel.x = 4;
    self.placeholderLabel.y = 8;
    self.placeholderLabel.width = self.width - 2*self.placeholderLabel.x;
    // 自適應
    [self.placeholderLabel sizeToFit];
}

- (void)textDidChange:(NSNotification *)note{
    // 是否隱藏
    self.placeholderLabel.hidden = self.hasText;
}

// 移除監聽者
- (void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}


- (void)setPlaceholderColor:(UIColor *)placeholderColor{
    self.placeholderLabel.textColor = placeholderColor;
}

#pragma mark ========== 重新計算placeholderLabel的尺寸 =============
- (void)setFont:(UIFont *)font{
    [super setFont:font];
    self.placeholderLabel.font = self.font;
    // 重新布局
    [self setNeedsLayout];
}

- (void)setPlaceholder:(NSString *)placeholder{
    self.placeholderLabel.text = [placeholder copy];
    // 重新布局
    [self setNeedsLayout];
}

#pragma mark ========== 隱藏placeholderLabel =============
- (void)setText:(NSString *)text{
    [super setText:text];
    // 根據是否有文字來判斷要不要隱藏
    self.placeholderLabel.hidden = self.hasText;
}

- (void)setAttributedText:(NSAttributedString *)attributedText{
    [super setAttributedText:attributedText];
    // 根據是否有文字來判斷要不要隱藏
    self.placeholderLabel.hidden = self.hasText;
}

@end

3.runTime

  • 頭文件
#import <objc/runtime.h>
#import <objc/message.h>```

- viewDidLoad

  • (void)viewDidLoad {
    [super viewDidLoad];  
    // 通過運行時,發現UITextView有一個叫做“_placeHolderLabel”的私有變量
    unsigned int count = 0;
    Ivar *ivars = class_copyIvarList([UITextView class], &count);
    for (int i = 0; i < count; i++) {
    Ivar ivar = ivars[i];
    const char *name = ivar_getName(ivar);
    NSString *objcName = [NSString stringWithUTF8String:name];
    NSLog(@"%d : %@",i,objcName);
    }
    [self setupTextView];
    }```

  • setupTextView

- (void)setupTextView{
        // 提示文字
        CGFloat margin  = 15;
        
        UILabel *tipLabel = [[UILabel alloc] initWithFrame:CGRectMake(margin, 0, MGSCREEN_width - 2 * margin, 50)];
        tipLabel.text = @"你的批評和建議能幫助我們更好的完善產品,請留下你的寶貴意見!";
        tipLabel.numberOfLines = 2;
        tipLabel.textColor = MGRGBColor(255, 10, 10);
        tipLabel.font = MGFont(16);
        [self.view addSubview:tipLabel];
        // 意見輸入框
        CGFloat height  = 200;
#ifndef __IPHONE_4_0
        height = 100;
#endif
        UITextView *iderTextView = [[UITextView alloc] initWithFrame:CGRectMake(margin, CGRectGetMaxY(tipLabel.frame) + margin, MGSCREEN_width - 2 * margin, height)];
        iderTextView.backgroundColor = [UIColor whiteColor];
        iderTextView.scrollEnabled = YES;
        iderTextView.scrollsToTop = YES;
        iderTextView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;
//    iderTextView.delegate = self;
        self.iderTextView = iderTextView;
        [self.view addSubview:iderTextView];
    
        // _placeholderLabel
        UILabel *placeHolderLabel = [[UILabel alloc] init];
        placeHolderLabel.text = @"請輸入寶貴意見(300字以內)";
        placeHolderLabel.numberOfLines = 0;
        placeHolderLabel.font = [UIFont systemFontOfSize:14];
        placeHolderLabel.textColor = [UIColor lightGrayColor];
        [placeHolderLabel sizeToFit];
        [iderTextView addSubview:placeHolderLabel];
    
        [iderTextView setValue:placeHolderLabel forKey:@"_placeholderLabel"];
        iderTextView.font =  placeHolderLabel.font;
}

補充:一種最簡單的實現占位文字的textView(該方法有點投機取巧)

  • viewDidLoad
- (void)viewDidLoad {
    [super viewDidLoad];
    //    意見輸入
    myTextView=[[UITextView alloc] initWithFrame:(CGRectMake(10, 33, kScreenWidth-20, 130))];
    myTextView.font=kFont(15);
    myTextView.delegate=self;
    myTextView.backgroundColor=self.view.backgroundColor;
    ViewBorderRadius(myTextView, 0, 0.5f, kGray);
    myTextView.textColor=kGray;
    myTextView.text=@" 請輸入詳細描述";
    myTextView.tintColor=kWhite;
    [self.view addSubview:myTextView];
    //    提交
    UIButton *feedBtn=[UIButton buttonWithType:(UIButtonTypeCustom)];
    feedBtn.frame=CGRectMake(100, myTextView.tail+40, kScreenWidth-200, 40);
    [feedBtn addTarget:self action:@selector(feedBtnHandled:) forControlEvents:(UIControlEventTouchUpInside)];
    [feedBtn setTitle:@"提交" forState:(UIControlStateNormal)];
    [feedBtn setTitleColor:[UIColor whiteColor] forState:(UIControlStateNormal)];
    feedBtn.titleLabel.font=kFont(18);
    feedBtn.backgroundColor=naBarTiniColor;
    [self.view addSubview:feedBtn];

}```

- UITextViewDelegate

  • (void)textViewDidBeginEditing:(UITextView *)textView{
    if([textView.text isEqualToString:@" 請輸入詳細描述"]){
    textView.text=@"";
    textView.textColor=kWhite;
    }
    }

  • (void)textViewDidEndEditing:(UITextView *)textView{

    if([textView.text isEmptyString]){

      textView.text=@" 請輸入詳細描述";
      textView.textColor=kGray;
    

    }
    }

![未輸入時](http://upload-images.jianshu.io/upload_images/1429890-73a3f245a9ced10a.PNG)
![UITextView成為第一響應者時](http://upload-images.jianshu.io/upload_images/1429890-10b06997fb7af974.PNG)
***
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容