UITextField扩展

开发中,我们会遇到设置UITextField的颜色,有的时候需要设置一下PlaceHolder的位置,如图所示:

UITextField扩展_第1张图片
Snip20160507_3.png

第一个UITextField设置PlaceHolder颜色,并且设置离左边的位置,切光标在PlaceHolder的起始点,第二个是正常的UITextField,第一种情况有人会自定义UITextField,其实不需要:

    self.leftTextField.leftPadding=20.0f;
    self.leftTextField.placeholder=@"FlyElephant-Left";
    self.leftTextField.placeHolderColor=[UIColor redColor];
    
    self.normalTextField.placeholder=@"FlyElephant-Normal";

UITextField分类:

//
//  UITextField+FEPlaceHolder.h
//  FECategory
//
//  Created by FlyElephant on 16/5/7.
//  Copyright © 2016年 FlyElephant. All rights reserved.
//

#import 

@interface UITextField (FEPlaceHolder)

/**
 *  modify default placeholder padding
 */
@property (assign,nonatomic) CGFloat leftPadding;
/**
 *  modify default placeholder color
 */
@property (strong,nonatomic) UIColor *placeHolderColor;

@end

实现:

//
//  UITextField+FEPlaceHolder.m
//  FECategory
//
//  Created by FlyElephant on 16/5/7.
//  Copyright © 2016年 FlyElephant. All rights reserved.
//

#import "UITextField+FEPlaceHolder.h"
#import 

static const void *leftPaddingKey= &leftPaddingKey;
static const void *rightPaddingKey= &rightPaddingKey;
static const void *placeHolderColorKey = &placeHolderColorKey;

@implementation UITextField (FEPlaceHolder)

-(CGFloat)leftPadding {
    return [objc_getAssociatedObject(self, leftPaddingKey) floatValue];
}

-(void)setLeftPadding:(CGFloat)leftPadding {
    CGRect frame = self.frame;
    frame.size.width =leftPadding;
    UIView *leftview = [[UIView alloc] initWithFrame:frame];
    self.leftViewMode = UITextFieldViewModeAlways;
    self.leftView = leftview;
    objc_setAssociatedObject(self,leftPaddingKey,[NSNumber numberWithFloat:leftPadding], OBJC_ASSOCIATION_ASSIGN);
}

-(CGFloat)rightPadding {
    return [objc_getAssociatedObject(self, rightPaddingKey) floatValue];
}

-(void)setRightPadding:(CGFloat)rightPadding {
    CGRect frame = self.frame;
    frame.size.width =rightPadding;
    UIView *leftview = [[UIView alloc] initWithFrame:frame];
    self.rightViewMode = UITextFieldViewModeAlways;
    self.rightView = leftview;
    objc_setAssociatedObject(self,rightPaddingKey,[NSNumber numberWithFloat:rightPadding], OBJC_ASSOCIATION_ASSIGN);
}

-(UIColor *)placeHolderColor {
    return objc_getAssociatedObject(self, placeHolderColorKey);
}

-(void)setPlaceHolderColor:(UIColor *)placeHolderColor{
    [self setValue:placeHolderColor forKeyPath:@"_placeholderLabel.textColor"];
    objc_setAssociatedObject(self,placeHolderColorKey, placeHolderColor, OBJC_ASSOCIATION_RETAIN);
}

@end

你可能感兴趣的:(UITextField扩展)