UITextField的简易封装

效果

源码

https://github.com/YouXianMing/UI-Component-Collection 中的 UITextFieldView

//
//  UITextFieldView.h
//  UITextField
//
//  Created by YouXianMing on 16/7/22.
//  Copyright © 2016年 YouXianMing. All rights reserved.
//

#import <UIKit/UIKit.h>
#import "AbsTextFieldViewValidator.h"
@class UITextFieldView;

@protocol UITextFieldViewDelegate <NSObject>

@optional

/**
 *  When change characters in range, you can get the current string.
 *
 *  @param textFieldView UITextFieldView‘s object.
 *  @param currentString The current string.
 */
- (void)textFieldView:(UITextFieldView *)textFieldView currentString:(NSString *)currentString;

@end

/**
 *  Asks the delegate if editing should begin in the specified text field.
 *
 *  @param textFieldView UITextFieldView object.
 *
 *  @return YES if editing should begin or NO if it should not.
 */
typedef BOOL (^textFieldShouldBeginEditing_t)(UITextFieldView *textFieldView);

/**
 *  Tells the delegate that editing began in the specified text field.
 *
 *  @param textFieldView UITextFieldView object.
 */
typedef void (^textFieldDidBeginEditing_t)(UITextFieldView *textFieldView);

/**
 *  Asks the delegate if editing should stop in the specified text field.
 *
 *  @param textFieldView UITextFieldView object.
 *
 *  @return YES if editing should stop or NO if it should continue.
 */
typedef BOOL (^textFieldShouldEndEditing_t)(UITextFieldView *textFieldView);

/**
 *  Tells the delegate that editing stopped for the specified text field.
 *
 *  @param textFieldView UITextFieldView object.
 */
typedef void (^textFieldDidEndEditing_t)(UITextFieldView *textFieldView);

/**
 *  Asks the delegate if the specified text should be changed.
 *
 *  @param textFieldView     UITextFieldView object.
 *  @param range             The range of characters to be replaced.
 *  @param replacementString The replacement string for the specified range. During typing, this parameter normally contains only the single new character that was typed, but it may contain more characters if the user is pasting text. When the user deletes one or more characters, the replacement string is empty.
 *  @param currentText       The current string.
 *
 *  @return YES if the specified text range should be replaced; otherwise, NO to keep the old text.
 */
typedef BOOL (^textFieldshouldChangeCharactersInRange_t)(UITextFieldView *textFieldView, NSRange range, NSString *replacementString, NSString *currentText);

/**
 *  Asks the delegate if the text field’s current contents should be removed.
 *
 *  @param textFieldView UITextFieldView object.
 *
 *  @return YES if the text field’s contents should be cleared; otherwise, NO.
 */
typedef BOOL (^textFieldShouldClear_t)(UITextFieldView *textFieldView);

/**
 *  Asks the delegate if the text field should process the pressing of the return button.
 *
 *  @param textFieldView YES if the text field should implement its default behavior for the return button; otherwise, NO.
 *
 *  @return UITextFieldView object.
 */
typedef BOOL (^textFieldShouldReturn_t)(UITextFieldView *textFieldView);

#pragma mark - UITextFieldView

@interface UITextFieldView : UIView

/**
 *  UITextFieldView‘s delegate.
 */
@property (nonatomic, weak) id <UITextFieldViewDelegate> delegate;

/**
 *  To set the textField‘s text & currentText‘s text.
 *
 *  @param text The text you set.
 */
- (void)setCurrentTextFieldText:(NSString *)text;

/**
 *  The textField, you can use it to set many properties.
 */
@property (nonatomic, strong, readonly) UITextField *textField;

/**
 *  The current string.
 */
@property (nonatomic, strong, readonly) NSString *currentText;

#pragma mark - TextField validator.

/**
 *  TextField validator.
 */
@property (nonatomic, strong) AbsTextFieldViewValidator *textFieldViewValidator;

/**
 *  Checking the textField‘s string.
 *
 *  @return TextField validator message.
 */
- (TextFieldValidatorMessage *)checkingTheTextFieldViewString;

#pragma mark - TextField delegate‘s block. 

/**
 *  Should begin editing block.
 */
@property (nonatomic, copy) textFieldShouldBeginEditing_t shouldBeginEditingBlock;

/**
 *  Did begin editing block.
 */
@property (nonatomic, copy) textFieldDidBeginEditing_t didBeginEditingBlock;

/**
 *  should end editing block.
 */
@property (nonatomic, copy) textFieldShouldEndEditing_t shouldEndEditingBlock;

/**
 *  Did end editing block.
 */
@property (nonatomic, copy) textFieldDidEndEditing_t didEndEditingBlock;

/**
 *  Should change characters in range block.
 */
@property (nonatomic, copy) textFieldshouldChangeCharactersInRange_t shouldChangeCharactersInRangeBlock;

/**
 *  Should clear block.
 */
@property (nonatomic, copy) textFieldShouldClear_t shouldClearBlock;

/**
 *  Should return block.
 */
@property (nonatomic, copy) textFieldShouldReturn_t shouldReturnBlock;

/**
 *  Convenient method to set blocks.
 *
 *  @param changeCharactersInRange Should change characters in range block.
 *  @param didBeginEditingBlock    Did begin editing block.
 *  @param didEndEditingBlock      Did end editing block.
 *  @param shouldReturnBlock       Did end editing block.
 */
- (void)registerShouldChangeCharactersInRange:(textFieldshouldChangeCharactersInRange_t)changeCharactersInRange
                              didBeginEditing:(textFieldDidBeginEditing_t)didBeginEditingBlock
                                didEndEditing:(textFieldDidEndEditing_t)didEndEditingBlock
                                 shouldReturn:(textFieldShouldReturn_t)shouldReturnBlock;

#pragma mark - Become & resign first responder.

/**
 *  Notifies the receiver that it is about to become first responder in its window.
 */
- (void)becomeFirstResponder;

/**
 *  Notifies the receiver that it has been asked to relinquish its status as first responder in its window.
 */
- (void)resignFirstResponder;

#pragma mark - InputAccessoryView.

- (void)createInputAccessoryViewWithViewHeight:(CGFloat)height block:(void (^)(UIView *inputAccessoryView, UITextFieldView *textFieldView))block;

#pragma mark - Transform position.

/**
 *  Rect from the view.
 *
 *  @param view The view you specified.
 *
 *  @return The rect.
 */
- (CGRect)rectFromView:(UIView *)view;

#pragma mark - Constructor method.

//- (instancetype)

@end
//
//  UITextFieldView.m
//  UITextField
//
//  Created by YouXianMing on 16/7/22.
//  Copyright © 2016年 YouXianMing. All rights reserved.
//

#import "UITextFieldView.h"

@interface UITextFieldView () <UITextFieldDelegate>

@property (nonatomic, strong) NSString    *currentText;
@property (nonatomic, strong) UITextField *textField;
@property (nonatomic)         BOOL         secureTextEntryBecomeActive;

@end

@implementation UITextFieldView

- (instancetype)initWithFrame:(CGRect)frame {

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

        self.textField          = [[UITextField alloc] initWithFrame:self.bounds];
        self.textField.delegate = self;
        [self addSubview:self.textField];
    }

    return self;
}

- (void)becomeFirstResponder {

    [self.textField becomeFirstResponder];
}

- (void)resignFirstResponder {

    [self.textField resignFirstResponder];
}

- (void)registerShouldChangeCharactersInRange:(textFieldshouldChangeCharactersInRange_t)block
                              didBeginEditing:(textFieldDidBeginEditing_t)didBeginEditingBlock
                                didEndEditing:(textFieldDidEndEditing_t)didEndEditingBlock
                                 shouldReturn:(textFieldShouldReturn_t)shouldReturnBlock {

    self.shouldChangeCharactersInRangeBlock = block;
    self.shouldReturnBlock                  = shouldReturnBlock;
    self.didBeginEditingBlock               = didBeginEditingBlock;
    self.didEndEditingBlock                 = didEndEditingBlock;
}

- (void)setCurrentTextFieldText:(NSString *)text {

    _currentText    = text;
    _textField.text = text;
}

- (void)createInputAccessoryViewWithViewHeight:(CGFloat)height block:(void (^)(UIView *inputAccessoryView, UITextFieldView *textFieldView))block {

    CGRect rect                       = CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, height);
    self.textField.inputAccessoryView = [[UIView alloc] initWithFrame:rect];
    block ? block(self.textField.inputAccessoryView, self) : 0;
}

- (TextFieldValidatorMessage *)checkingTheTextFieldViewString {

    return [self.textFieldViewValidator validatorWithInputSting:self.currentText];
}

- (CGRect)rectFromView:(UIView *)view {

    return [self convertRect:self.bounds toView:view];
}

#pragma mark - UITextFieldDelegate

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {

    if (self.shouldBeginEditingBlock) {

        return self.shouldBeginEditingBlock(self);

    } else {

        return YES;
    }
}

- (void)textFieldDidBeginEditing:(UITextField *)textField {

    if (self.didBeginEditingBlock) {

        self.didBeginEditingBlock(self);
    }

    if (self.textField.secureTextEntry == YES) {

        _secureTextEntryBecomeActive = YES;
    }
}

- (BOOL)textFieldShouldEndEditing:(UITextField *)textField {

    if (self.shouldEndEditingBlock) {

        return self.shouldEndEditingBlock(self);

    } else {

        return YES;
    }
}

- (void)textFieldDidEndEditing:(UITextField *)textField {

    if (self.didEndEditingBlock) {

        self.didEndEditingBlock(self);
    }
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {

    if (self.textField.secureTextEntry == YES && _secureTextEntryBecomeActive == YES) {

        // 密码键盘特殊处理
        self.currentText                 = [NSMutableString stringWithString:string.length <= 0 ? @"" : string];
        self.secureTextEntryBecomeActive = NO;

    } else {

        // 普通键盘
        NSString *currentText = [textField.text stringByReplacingCharactersInRange:range withString:string];
        self.currentText      = currentText;
    }

    if (self.delegate && [self.delegate respondsToSelector:@selector(textFieldView:currentString:)]) {

        [self.delegate textFieldView:self currentString:self.currentText];
    }

    if (self.shouldChangeCharactersInRangeBlock) {

        return self.shouldChangeCharactersInRangeBlock(self, range, string, self.currentText);

    } else {

        return YES;
    }
}

- (BOOL)textFieldShouldClear:(UITextField *)textField {

    if (self.shouldClearBlock) {

        return self.shouldClearBlock(self);

    } else {

        return YES;
    }
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField {

    if (self.shouldReturnBlock) {

        return self.shouldReturnBlock(self);

    } else {

        return YES;
    }
}

@end
//
//  TextFieldValidatorMessage.h
//  ZiPeiYi
//
//  Created by YouXianMing on 16/1/8.
//  Copyright © 2016年 YouXianMing. All rights reserved.
//

#import <Foundation/Foundation.h>

@interface TextFieldValidatorMessage : NSObject

/**
 *  Is valid string or not.
 */
@property (nonatomic) BOOL isValidString;

/**
 *  Error message.
 */
@property (nonatomic, strong) NSString *errorMessage;

/**
 *  Convenient method.
 *
 *  @param errorMessage  Error message string.
 *  @param isValidString Is valid string or not.
 *
 *  @return TextFieldValidatorMessage.
 */
+ (TextFieldValidatorMessage *)textFieldValidatorMessageWithErrorMessage:(NSString *)errorMessage
                                                           isValidString:(BOOL)isValidString;

@end

/**
 *  Convenient method.
 *
 *  @param isValidString Is valid string or not.
 *  @param errorMessage  Error message string.
 *
 *  @return TextFieldValidatorMessage.
 */
NS_INLINE TextFieldValidatorMessage * textFieldValidatorMessageIsValid(BOOL isValidString, NSString *errorMessage) {

    return [TextFieldValidatorMessage textFieldValidatorMessageWithErrorMessage:errorMessage
                                                                  isValidString:isValidString];
}
//
//  TextFieldValidatorMessage.m
//  ZiPeiYi
//
//  Created by YouXianMing on 16/1/8.
//  Copyright © 2016年 YouXianMing. All rights reserved.
//

#import "TextFieldValidatorMessage.h"

@implementation TextFieldValidatorMessage

+ (TextFieldValidatorMessage *)textFieldValidatorMessageWithErrorMessage:(NSString *)errorMessage isValidString:(BOOL)isValidString {

    TextFieldValidatorMessage *message = [[self class] new];
    message.errorMessage               = errorMessage;
    message.isValidString              = isValidString;

    return message;
}

@end
//
//  AbsTextFieldViewValidator.h
//  UITextField
//
//  Created by YouXianMing on 16/7/23.
//  Copyright © 2016年 YouXianMing. All rights reserved.
//

#import <Foundation/Foundation.h>
#import "TextFieldValidatorMessage.h"

@interface AbsTextFieldViewValidator : NSObject

- (TextFieldValidatorMessage *)validatorWithInputSting:(NSString *)inputString;

@end
//
//  AbsTextFieldViewValidator.m
//  UITextField
//
//  Created by YouXianMing on 16/7/23.
//  Copyright © 2016年 YouXianMing. All rights reserved.
//

#import "AbsTextFieldViewValidator.h"

@implementation AbsTextFieldViewValidator

- (TextFieldValidatorMessage *)validatorWithInputSting:(NSString *)inputString {

   return textFieldValidatorMessageIsValid(YES, nil);
}

@end
时间: 2024-10-14 05:36:55

UITextField的简易封装的相关文章

对JdbcTemplate进行简易封装以使其更加易用

在上一篇博文<基于SpringJDBC的类mybatis形式SQL语句管理的思考与实现>中,我们实现了采用XML文件对SQL进行管理.在本篇博文中,我们将对SpringJDBC提供的JdbcTemplate进行简易封装,使其更加的易用,更加贴近上篇博文中对于SQL管理的设计. 我们希望在使用将要封装的这个工具进行数据库操作时有以下几个优势: 不处理数据获取异常 不关心日志记录 即可以使用我们XML文件中的SQL语句,也可以使用在业务方法中定义的SQL语句.(因为我们设计的XML文件并不能够非常

AVAudioPlayer简易封装

[说明] AVAudioPlayer简易封装,仅仅支持播放,暂停,停止,暂停时候带有渐隐效果,自己用,没有参考价值. [源码] https://github.com/YouXianMing/AVAudioPlayer- 一个定时器的封装类源码(该定时器可以指定运行的次数) // // SpecialTimer.h // Music // // Created by XianMingYou on 15/4/13. // Copyright (c) 2015年 XianMingYou. All ri

面localStorage用作数据缓存的简易封装

面localStorage用作数据缓存的简易封装 最近做了一些前端控件的封装,需要用到数据本地存储,开始采用cookie,发现很容易就超过了cookie的容量限制,于是改用localStorage,但localStorage过于简单,没有任何管理和限制,因此封装了下面这个对象. 我的封装非常直观简单,比网上的一些晦涩的代码明显小巧精简实用.目前只自动回收过期或最后一次访问时间到现在的间隔最大的项,以后有时间,再把访问次数纳入到自动回收的算法中. window.MyCache = window.M

快速简易封装歌词文件

月半夜小夜曲.lrc [ti:月半夜小夜曲] [ar:李克勤] [by:TTPod] [00:01.48]月半小夜曲 [00:05.66]作词:向雪怀 [00:10.66]作曲:河合奈保子 [00:15.63]演唱:李克勤 [00:20.63] [00:24.56]仍然倚在失眠夜望天边星宿 [00:30.46]仍然听见小提琴如泣似诉再挑逗 [00:36.30]为何只剩一弯月留在我的天空 [00:42.92]这晚以后音讯隔绝 [00:48.29]人如天上的明月是不可拥有 [00:54.26]情如曲

对xlslib库与libxls库的简易封装

一.简介 xlslib库是用来创建excel文件.libxls是用来读取excel文件的,在使用C++或者QT语言来设计对excel文件的读取.都需要事先下载这两个库编译成功后再进行程序设计的.之所以选择这两个库来使用,是因为这两个库即可以在windows系统下使用,又可以在Linux系统下使用.对于设计跨平台使用的程序来说这两个库是一个不错的选择.具体的编译方法,网上有很多资源,再次不在赘述. 二.使用示例 本程序中我对这两个库做了简易的封装,生成了两个动态库,主要功能就是对excel文件的创

富文本的封装-NSAttributedString 的简易封装

有时我们经常写富文老是写出这样子的出来,极易出错而且可读性非常差,如下: - (void)typeOne{ NSString *string                            = @"你好,CSDN!"; NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:string]; // 设置富文本样式 [attributedStrin

Linux网络编程8&mdash;&mdash;对TCP与UDP的简易封装

引言 每次使用socket通信,都会有很对相似的操作.本文,会对TCP与UDP通信做一简单封装,并生成动态库. 代码 my_socket.h #ifndef __MY_SOCKET_H__ #define __MY_SOCKET_H__ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <sys/socket.h> #in

Nhibernate基础使用教程以及简易封装

1.Nhibernate简介 NHibernate是一个面向.NET环境的对象/关系数据库映射工具.对象/关系数据库映射(object/relational mapping,ORM)这个术语表示一种技术,用来把对象模型表示的对象映射到基于SQL的关系模型数据结构中去 简单的说就是将数据库的结构直接映射到实体模型之上,从而简化SQL的数据处理时间.通过XML(Fluent亦可)进行定义数据模型的持久化,nhibernate 内部的映射结构以及如图1-1所示: 2.准备 Nhibernate类库,下

iOS-UIAlertController简易封装

//提醒框封装方法 -(void)showAlertControllerWithMessage:(NSString *)message{ UIAlertController *remindAV = [UIAlertController alertControllerWithTitle:@"提示" message:message preferredStyle:UIAlertControllerStyleAlert]; [remindAV addAction:[UIAlertAction