关于UITextField的封装

本文介绍了一个自定义的 UITextField 类 KPTextField,它提供了丰富的自定义选项,如占位符颜色、边框样式、输入限制等,并实现了文字长度限制及密码显示切换功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

直接上代码:

.H文件:

//
//  KPTextField.h
//
//  如果有占位字符,请先设置占位字符内容,再设置相关属性
//
//  Created by 刘鲲鹏 on 2017/5/16.
//  Copyright © 2017年 刘鲲鹏. All rights reserved.
//

#import <UIKit/UIKit.h>

#define KPTextFieldPaddingWidth  (10.0f)
#define KPTextFieldPaddingHeight (5.0f)

typedef void(^KP_textFieldLengthOverLimitBlock)(NSInteger maxLengthOfText);


@interface KPTextField : UITextField


/** 占位文字普通颜色 */
@property (nonatomic, strong) UIColor *placeHolderNormalColor;

/** 成为第一响应者时占位文字的文字颜色 */
@property (nonatomic, strong) UIColor *placeHolderHighlightedColor;

/** 占位文字字体大小 */
@property (nonatomic, assign) CGFloat placeHolderFontSize;

/** 左右缩进 默认为10 */
@property (nonatomic, assign) CGFloat paddingWith;

/** 上下缩进 默认为5 */
@property (nonatomic, assign) CGFloat paddingHeight;

/** 左侧内边距(不推荐使用,建议使用paddingWith) */
@property (nonatomic, assign) CGFloat leftMargin;

/** 右侧内边距(不推荐使用,建议使用paddingWith) */
@property (nonatomic, assign) CGFloat rightMargin;

/** clearButton普通状态图片 */
@property (nonatomic, copy) NSString *clearButtonNormalImageName;

/** clearButton高亮状态图片 */
@property (nonatomic, copy) NSString *clearButtonHighlightedImageName;

/** 设置边框宽度,默认没有边框 */
@property (nonatomic, assign) NSUInteger borderWidth;

/** 设置边框颜色,默认为亮灰色 */
@property (nonatomic, strong) UIColor *borderColor;

/** 设置圆角,默认没有圆角 */
@property (nonatomic, assign) NSUInteger cornerRadius;

/** 光标宽度,默认为2 */
@property (nonatomic, assign) NSUInteger cursorWidth;

/** 光标高度,默认为 self.font.lineHeight + 4 */
@property (nonatomic, assign) NSUInteger cursorHeight;

/** textField可以输入的最大字数,默认没有字数限制 */
@property (nonatomic, assign) NSUInteger maxLengthOfText;

/**
 *  文字字数超出设定值会自动调用
 *  block参数(maxLengthOfText) → 文字长度最大值
 */
@property (nonatomic, strong) KP_textFieldLengthOverLimitBlock textOverLimitBlock;

/** 禁止粘贴,默认为NO */
@property (nonatomic, assign) BOOL forbidPaste;

/** 设置为密码输入样式 */
@property (nonatomic, assign) BOOL PasswordMode;


@end

.M文件:

//
//  KPTextField.m
//  TextField
//
//  Created by 刘鲲鹏 on 2017/5/16.
//  Copyright © 2017年 刘鲲鹏. All rights reserved.
//

#import "KPTextField.h"

@implementation KPTextField

- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {

        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didBeginEditing) name:UITextFieldTextDidBeginEditingNotification object:self];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didEndEditing) name:UITextFieldTextDidEndEditingNotification object:self];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textDidChange) name:UITextViewTextDidChangeNotification object:self];
    }
    return self;
}

- (void)textDidChange{
    NSInteger wordCount = self.text.length;
    NSLog(@"%ld",(long)wordCount);
    if (_maxLengthOfText && wordCount >= _maxLengthOfText) {
        self.text = [self.text substringToIndex:_maxLengthOfText];
        if (_textOverLimitBlock) {
            _textOverLimitBlock(_maxLengthOfText);
        }
    }
}

- (void)setPlaceHolderNormalColor:(UIColor *)placeHolderNormalColor {
    _placeHolderNormalColor = placeHolderNormalColor;
    if (self.placeholder) {
        self.attributedPlaceholder = [[NSAttributedString alloc] initWithString:self.placeholder attributes:@{NSForegroundColorAttributeName:_placeHolderNormalColor}];
    }

}

- (void)didBeginEditing {
    if (self.placeholder) {
        self.attributedPlaceholder = [[NSAttributedString alloc] initWithString:self.placeholder attributes:@{NSForegroundColorAttributeName:_placeHolderHighlightedColor}];
    }

}

- (void)didEndEditing {
    if (self.placeholder) {
        self.attributedPlaceholder = [[NSAttributedString alloc] initWithString:self.placeholder attributes:@{NSForegroundColorAttributeName:_placeHolderNormalColor}];
    }

}

- (void)setPlaceHolderFontSize:(CGFloat)placeHolderFontSize {
    _placeHolderFontSize = placeHolderFontSize;
    if (self.placeholder) {
        self.attributedPlaceholder = [[NSAttributedString alloc] initWithString:self.placeholder attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:_placeHolderFontSize]}];
    }
}


//控制 placeHolder 的位置,左右缩进
- (CGRect)textRectForBounds:(CGRect)bounds {
    return CGRectInset(bounds,
                       self.paddingWith == 0.0f ? KPTextFieldPaddingWidth : self.paddingWith,
                       self.paddingHeight == 0.0f ? KPTextFieldPaddingHeight : self.paddingHeight);
}

// 控制文本的位置,左右缩进
- (CGRect)editingRectForBounds:(CGRect)bounds {
    return CGRectInset(bounds,
                       self.paddingWith == 0.0f ? KPTextFieldPaddingWidth : self.paddingWith,
                       self.paddingHeight == 0.0f ? KPTextFieldPaddingHeight : self.paddingHeight);
}

- (void)setPaddingWith:(CGFloat)paddingWith {
    _paddingWith = paddingWith;
    [self setNeedsDisplay];
}

- (void)setPaddingHeight:(CGFloat)paddingHeight {
    _paddingHeight = paddingHeight;
    [self setNeedsDisplay];
}

- (void)setLeftMargin:(CGFloat)leftMargin {
    _leftMargin = leftMargin;
    [self setValue:[NSNumber numberWithFloat:leftMargin] forKey:@"paddingLeft"];
}

- (void)setRightMargin:(CGFloat)rightMargin {
    _rightMargin = rightMargin;
    [self setValue:[NSNumber numberWithFloat:rightMargin] forKey:@"paddingRight"];
}


- (void)setClearButtonNormalImageName:(NSString *)clearButtonNormalImageName {
    _clearButtonNormalImageName = clearButtonNormalImageName;
    UIButton *clearButton = [self valueForKey:@"_clearButton"];
    [clearButton setImage:[UIImage imageNamed:clearButtonNormalImageName] forState:UIControlStateNormal];
}

- (void)setClearButtonHighlightedImageName:(NSString *)clearButtonHighlightedImageName {
    _clearButtonHighlightedImageName = clearButtonHighlightedImageName;
    UIButton *clearButton = [self valueForKey:@"_clearButton"];
    [clearButton setImage:[UIImage imageNamed:clearButtonHighlightedImageName] forState:UIControlStateHighlighted];
}

- (void)setBorderWidth:(NSUInteger)borderWidth {
    _borderWidth = borderWidth;
    self.layer.borderWidth = _borderWidth;
}

- (void)setBorderColor:(UIColor *)borderColor {
    _borderColor = borderColor;
    self.layer.borderColor = _borderColor.CGColor;
}

- (void)setCornerRadius:(NSUInteger)cornerRadius {
    _cornerRadius = cornerRadius;
    self.layer.cornerRadius = cornerRadius;
}

- (CGRect)caretRectForPosition:(UITextPosition *)position
{
    CGRect originalRect = [super caretRectForPosition:position];

    if (_cursorHeight) {
        originalRect.size.height = _cursorHeight;
    }else {
        originalRect.size.height = self.font.lineHeight + 4;
    }
    if (_cursorWidth) {
        originalRect.size.width = _cursorWidth;
    }else {
        originalRect.size.width = 2;
    }

    return originalRect;
}

- (void)textLengthOverLimit:(KP_textFieldLengthOverLimitBlock)block {
    _textOverLimitBlock = block;
}


- (BOOL)canPerformAction:(SEL)action withSender:(id)sender
{
    if (action == @selector(paste:))//禁止粘贴
        return !_forbidPaste;
    if (action == @selector(select:))// 禁止选择
        return NO;
    if (action == @selector(selectAll:))// 禁止全选
        return NO;
    return [super canPerformAction:action withSender:sender];
}

- (void)setPasswordMode:(BOOL)PasswordMode {
    _PasswordMode = PasswordMode;
    if (_PasswordMode) {
        self.placeholder = @"请输入密码";
        self.secureTextEntry = YES;
        self.clearButtonMode = UITextFieldViewModeNever;
        UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, self.frame.size.height, self.frame.size.height)];
        imageView.image = [UIImage imageNamed:@"4321"];
        self.rightView = imageView;
        self.rightViewMode = UITextFieldViewModeAlways;
        imageView.userInteractionEnabled = YES;
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(changPasswordMode:)];
        [imageView addGestureRecognizer:tap];
    }
}

- (void)changPasswordMode:(UITapGestureRecognizer *)tapGesture {
    UIImageView *imageView = (UIImageView *)tapGesture.view;
    _PasswordMode = !_PasswordMode;
    if (!_PasswordMode) {
        self.secureTextEntry = NO;
        imageView.image = [UIImage imageNamed:@"1234"];
    }else if (_PasswordMode) {
        self.secureTextEntry = YES;
        imageView.image = [UIImage imageNamed:@"4321"];
    }
}



- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

@end
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值