UITextView-placeholder的實(shí)現(xiàn)和解析

前言

項(xiàng)目中UITextfield使用的比較頻繁,對于placeholder可以直接設(shè)置,文字,顏色,字體等等,但是UITextView繼承自UIScrollView,并沒有placeholder屬性。項(xiàng)目中以前就有使用到UITextView的placeholder,當(dāng)時只是外加了一個UILabel,但是每次都需要重新定制label,所以想著能夠?qū)懸粋€類別,添加一個label,實(shí)現(xiàn)字體,顏色,位置的可調(diào)節(jié)。
這里主要是在GitHub上面發(fā)現(xiàn)一個很好的類別,該類別的編寫者也是我所喜歡的一位iOS開發(fā)者。自己嘗試寫了一次,有了一定的了解,所以記錄下來,方便以后查閱。

Demo地址:碼云demo下載地址

首先先上圖看看效果:
默認(rèn)效果圖:


defalut_placeholder.png

設(shè)置顏色和location圖:


color_location_placeholder.png
placeholder.gif

下面開始解析代碼
根據(jù)意圖,也是在UITextView中添加一個UILabel,然后添加文字,顏色,富文本,位置等屬性,實(shí)現(xiàn)placeholder的可定制。

.h 解析

  • (readOnly)UILabel *placeholdLabel
  • NSString *placeholder placeholder 文字
  • UIColor *placeholderColor 顏色
  • NSAttributedString *attributePlaceholder 富文本
  • CGPoint location 位置
#import <UIKit/UIKit.h>

@interface UITextView (WJPlaceholder)

@property(nonatomic,readonly)  UILabel *placeholdLabel;
@property(nonatomic,strong) IBInspectable NSString *placeholder;
@property(nonatomic,strong) IBInspectable UIColor *placeholderColor;
@property(nonnull,strong) NSAttributedString *attributePlaceholder;
@property(nonatomic,assign) CGPoint location;
+ (UIColor *)defaultColor; //獲取默認(rèn)顏色(選取UITextFiled的placeholder顏色)
@end

使用IBInspectable修飾,可以使該屬性在interface builder中進(jìn)行編輯。placeholder和placeholder color都可以在user defined runtime attributes中進(jìn)行配置,如下圖:

UITextViewKeyPath.png
kvc_placeholder.png

.m 解析

首先設(shè)置三個key值,用于關(guān)聯(lián)屬性的創(chuàng)建和獲取

static char *labelKey = "placeholderKey";
static char *needAdjust = "needAdjust";
static char *changeLocation = "location";

創(chuàng)建的類別是不支持添加屬性的,要實(shí)現(xiàn)屬性的可設(shè)置,可以使用runtime來動態(tài)設(shè)置和獲取屬性值。
runtime添加關(guān)聯(lián)屬性

void objc_setAssociatedObject(id object, const void *key, id value, objc_AssociationPolicy policy)

第一個參數(shù)(object)表示要添加屬性的類,第二參數(shù)(const void *key)為一個key值,用來獲取設(shè)置的屬性值,第三個參數(shù)(value)為屬性的值,第四個參數(shù)(objc_AssociationPolicy policy)為屬性的修飾類型:一共有5個可選項(xiàng):

typedef OBJC_ENUM(uintptr_t, objc_AssociationPolicy) {
    OBJC_ASSOCIATION_ASSIGN = 0,           /**< Specifies a weak reference to the associated object. */
    OBJC_ASSOCIATION_RETAIN_NONATOMIC = 1, /**< Specifies a strong reference to the associated object. 
                                            *   The association is not made atomically. */
    OBJC_ASSOCIATION_COPY_NONATOMIC = 3,   /**< Specifies that the associated object is copied. 
                                            *   The association is not made atomically. */
    OBJC_ASSOCIATION_RETAIN = 01401,       /**< Specifies a strong reference to the associated object.
                                            *   The association is made atomically. */
    OBJC_ASSOCIATION_COPY = 01403          /**< Specifies that the associated object is copied.
                                            *   The association is made atomically. */
};

分別對應(yīng)assign,retain_nonatomic,copy_nonatomic,retain,copy。

runtime獲取成員屬性方法為:

id objc_getAssociatedObject(id object, const void *key)

第一個參數(shù)(object)為屬性所屬的類,一般使用self,第二個參數(shù)(key)為key值,和設(shè)置關(guān)聯(lián)屬性時使用的key一樣。

placeholderLabel為readOnly,重寫其get方法。

/**
 *  設(shè)置placeholderLabel
 *
 *  @return label
 */
- (UILabel *)placeholdLabel
{
    UILabel *label = objc_getAssociatedObject(self, labelKey);
    if (!label) {
        label = [[UILabel alloc] init];
        label.textAlignment = NSTextAlignmentLeft;
        label.numberOfLines = 0;
        label.textColor = [self.class defaultColor];
        objc_setAssociatedObject(self, labelKey, label, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
        //添加通知
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateLabel) name:UITextViewTextDidChangeNotification object:nil];
        //監(jiān)聽font的變化
        [self addObserver:self forKeyPath:@"font" options:NSKeyValueObservingOptionNew context:nil];
    }
    return label;
}

/**
 *  設(shè)置默認(rèn)顏色
 *
 *  @return color
 */
+ (UIColor *)defaultColor
{
    static UIColor *color = nil;
    static dispatch_once_t once_t;
    dispatch_once(&once_t, ^{
       UITextField *textField = [[UITextField alloc] init];
       textField.placeholder = @" ";
       color = [textField valueForKeyPath:@"_placeholderLabel.textColor"];
    });
    return color;
}

創(chuàng)建UILabel時,設(shè)置基本屬性,這里采用UITextfiled的placeholder的顏色作為默認(rèn)顏色。
同時添加對UITextView的狀態(tài)通知,UITextView主要有以下幾個通知可供使用

UIKIT_EXTERN NSNotificationName const UITextViewTextDidBeginEditingNotification;
UIKIT_EXTERN NSNotificationName const UITextViewTextDidChangeNotification;
UIKIT_EXTERN NSNotificationName const UITextViewTextDidEndEditingNotification;

這里使用UITextViewTextDidChangeNotification,在text改變的時候執(zhí)行updateLabel方法,進(jìn)行l(wèi)abel的顯示和隱藏以及其他設(shè)置。
對于UITextView的字體,使用KVO監(jiān)聽UITextView的font屬性,在設(shè)置時改變placeholderLabel的font。

以下是一些成員屬性的set get方法,通過set方法,將text,color,attributedText賦給placeholderLabel。
該類別主要使用runtime創(chuàng)建了3個關(guān)聯(lián)屬性,分別為

  • placeholderLabel
  • location CGPoint 位置
  • needAdJust BOOL 判斷是否需要調(diào)整
- (void)setPlaceholder:(NSString *)placeholder
{
    self.placeholdLabel.text = placeholder;
    [self updateLabel];
}

- (NSString *)placeholder
{
    return self.placeholdLabel.text;
}

- (void)setPlaceholderColor:(UIColor *)placeholderColor
{
    self.placeholdLabel.textColor = placeholderColor;
    [self updateLabel];
}

- (UIColor *)placeholderColor
{
    return self.placeholdLabel.textColor;
}

- (void)setAttributePlaceholder:(NSAttributedString *)attributePlaceholder
{
    self.placeholdLabel.attributedText = attributePlaceholder;
    [self updateLabel];
}

- (NSAttributedString *)attributePlaceholder
{
    return self.placeholdLabel.attributedText;
}

- (void)setLocation:(CGPoint)location
{
    objc_setAssociatedObject(self, changeLocation,NSStringFromCGPoint(location), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    [self updateLabel];
}

-(CGPoint)location
{
    return CGPointFromString(objc_getAssociatedObject(self, changeLocation));
}

//是否需要調(diào)整字體
- (BOOL)needAdjustFont
{
    return [objc_getAssociatedObject(self, needAdjust) boolValue ];
}

- (void)setNeedAdjustFont:(BOOL)needAdjustFont
{
    objc_setAssociatedObject(self, needAdjust, @(needAdjustFont), OBJC_ASSOCIATION_ASSIGN);
}

KVO 監(jiān)聽方法,判斷是否是font,執(zhí)行updataLabel方法。

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context
{
    if ([keyPath isEqualToString:@"font"])
    {
        self.needAdjustFont = YES;
         [self updateLabel];
    }
}

下面則是更新placeholderLabel的主要方法,調(diào)整位置,字體等。

/**
 *  更新label信息
 */
- (void)updateLabel
{
    if (self.text.length) {
        [self.placeholdLabel removeFromSuperview];
        return;
    }
    //顯示label
    [self insertSubview:self.placeholdLabel atIndex:0];
    
    //是否需要更新字體(NO 采用默認(rèn)字體大?。?    if (self.needAdjustFont) {
        self.placeholdLabel.font = self.font;
        self.needAdjustFont = NO;
    }

   CGFloat  lineFragmentPadding =  self.textContainer.lineFragmentPadding;  //邊距
   UIEdgeInsets contentInset = self.textContainerInset;

    //設(shè)置label frame
    CGFloat labelX = lineFragmentPadding + contentInset.left;
    CGFloat labelY = contentInset.top;
    if (self.location.x != 0 || self.location.y != 0) {
        if (self.location.x < 0 || self.location.x > CGRectGetWidth(self.bounds) - lineFragmentPadding - contentInset.right || self.location.y< 0) {
            // 不做處理
        }else{
            labelX += self.location.x;
            labelY += self.location.y;
        }
    }
    CGFloat labelW = CGRectGetWidth(self.bounds)  - contentInset.right - labelX;
    CGFloat labelH = [self.placeholdLabel sizeThatFits:CGSizeMake(labelW, MAXFLOAT)].height;
    self.placeholdLabel.frame = CGRectMake(labelX, labelY, labelW, labelH);
}

對于placeholderLabel的frame設(shè)置,需要考慮幾個方面:

  • lineFragmentPadding UITextView textContainer邊距
  • contentInset 輸入?yún)^(qū)域偏移 UIEdgeInsets
  • location 設(shè)置的位置
  • labeltextHeight placeholder的text高度

placeholder的frame.orgin.x = 邊距l(xiāng)ineFragmentPadding + contentInset.left + location.x;
frame.orgin.y = contentInset.top + location.y;
frame.size.width = UITextView的寬度 - placeholder的frame.orgin.x - contentInset.right;
frame.height = placeholder.text的高度

以上就是關(guān)于整個UITextView_placeholder的學(xué)習(xí)解剖,學(xué)到了一些新的知識,如果大家有什么意見和建議可以給我留言,指出我的不對的地方,大家一起學(xué)習(xí)交流。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容