UITextField扩展

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

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 <UIKit/UIKit.h>

@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 <objc/runtime.h>

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
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容