UITextField扩展

作者: FlyElephant | 来源:发表于2016-05-07 10:08 被阅读368次

开发中,我们会遇到设置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分类:
<pre><code>`

//
// 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
`</code></pre>

实现:
<pre><code>`
//
// 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
`</code></pre>

相关文章

网友评论

    本文标题:UITextField扩展

    本文链接:https://www.haomeiwen.com/subject/yoijrttx.html