UITextField自定义使用(一)

版本记录

版本号 时间
V1.0 2017.06.17

前言

很多时候我们做APP,比如注册、登录,还有很多绑定手机号等等逻辑后者功能模块的时候,都需要输入框,ios中输入框有两种,一种是UITextField,另外一种是UITextView,前者继承自UIControl,可以响应事件并且不可换行和滚动,后者继承自UIScrollView,可以滚动和换行不可以响应事件。
这一篇我们主要说一下UITextField的使用。

一、UITextField的基本使用

首先我们就说一下UITextField的基本使用方法。先看一下代码组织结构。

UITextField自定义使用(一)_第1张图片
代码组织结构

下面直接看代码。

1.JJTextVC.h
#import 

@interface JJTextVC : UIViewController

@end

2. JJTextVC.m
  #import "JJTextVC.h"
#import "JJTextField.h"
#import "Masonry.h"


@interface JJTextVC ()

@property (nonatomic, strong) JJTextField *inputTextField;
@property (nonatomic, strong) UILabel *tipLabel;



@end

@implementation JJTextVC

#pragma mark - Override Base Function

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor lightGrayColor];
    
    [self setupUI];
}

- (void)viewWillLayoutSubviews
{
    [super viewWillLayoutSubviews];
    
    //标签
    [self.tipLabel sizeToFit];
    [self.tipLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view).offset(20.0);
        make.top.equalTo(self.view).offset(100.0);
    }];
    
    //输入框
    [self.inputTextField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.tipLabel.mas_right).offset(15.0);
        make.centerY.equalTo(self.tipLabel);
        make.height.equalTo(@(CGRectGetHeight(self.tipLabel.frame)));
        make.width.equalTo(@(200.0));
    }];
}

#pragma mark - Object Private Function

- (void)setupUI
{
    //标签
    UILabel *tipLabel = [[UILabel alloc] init];
    tipLabel.text = @"手机号";
    tipLabel.textAlignment = NSTextAlignmentLeft;
    tipLabel.textColor =  [UIColor blueColor];
    tipLabel.font = [UIFont systemFontOfSize:18.0];
    [self.view addSubview:tipLabel];
    self.tipLabel = tipLabel;
    
    //输入框
    JJTextField *inputTextField = [[JJTextField alloc] init];
    inputTextField.placeholder = @"请输入手机号";
    [inputTextField addTarget:self action:@selector(textFieldDidChanged:) forControlEvents:UIControlEventEditingChanged];
    [self.view addSubview:inputTextField];
    self.inputTextField = inputTextField;
}

#pragma mark - Action && Notification

- (void)textFieldDidChanged:(JJTextField *)textField
{

}

@end

3. JJTextField.h
#import 

@interface JJTextField : UITextField

@end

4. JJTextField.m

#import "JJTextField.h"

@implementation JJTextField

@end

下面就看一下结果

UITextField自定义使用(一)_第2张图片
输出结果

有没有觉着这个文本输入框简直丑爆了,下面我们就进行优化和改进。


二、UITextField增加边框

下面我们就为文本输入框增加边框,让他看起来是有边界的。还是直接看代码。


    inputTextField.layer.borderColor = [UIColor blackColor].CGColor;
    inputTextField.layer.borderWidth = 0.5;

看效果图

UITextField自定义使用(一)_第3张图片
增加边框

可见,这个是可行的。

三、UITextField改变占位文字字体和颜色

下面还是直接看代码,直接用KVC进行操作。

    [inputTextField setValue:[UIColor blueColor] forKeyPath:@"_placeholderLabel.textColor"];
    [inputTextField setValue:[UIFont systemFontOfSize:15.0] forKeyPath:@"_placeholderLabel.font"];

看效果图

UITextField自定义使用(一)_第4张图片
改变占位文字字体和颜色

四、UITextField更改键盘样式和输入安全模式

还是直接看代码。

    inputTextField.keyboardType = UIKeyboardTypeNumberPad;
    inputTextField.secureTextEntry = YES;

下面看效果

UITextField自定义使用(一)_第5张图片
效果展示

五、UITextField占位文字在文本输入框中的位置

  我们这里就让占位文字向右一点,不让他紧靠左边边缘,这里的方法就是自定义UITextField实现重写其内部的方法,来对UITextField进行自定义设置。

我们先看一下UITextField中都有哪些方法。

#import 
#import 
#import 
#import 
#import 
#import 
#import 
#import 

NS_ASSUME_NONNULL_BEGIN

@class UIImage, UIImageView, UILabel, UIColor, UIButton;
@class UITextFieldAtomBackgroundView;
@class UITextFieldBackgroundView;
@class UITextFieldBorderView;
@class UITextFieldLabel;
@class UITextInputTraits;
@class UITextSelectionView;
@class UITextInteractionAssistant;
@class UIPopoverController;
@protocol UITextFieldDelegate;
@protocol UITextSelecting;

typedef NS_ENUM(NSInteger, UITextBorderStyle) {
    UITextBorderStyleNone,
    UITextBorderStyleLine,
    UITextBorderStyleBezel,
    UITextBorderStyleRoundedRect
};

typedef NS_ENUM(NSInteger, UITextFieldViewMode) {
    UITextFieldViewModeNever,
    UITextFieldViewModeWhileEditing,
    UITextFieldViewModeUnlessEditing,
    UITextFieldViewModeAlways
};

typedef NS_ENUM(NSInteger, UITextFieldDidEndEditingReason) {
    UITextFieldDidEndEditingReasonCommitted,
    UITextFieldDidEndEditingReasonCancelled UIKIT_AVAILABLE_TVOS_ONLY(10_0)
} NS_ENUM_AVAILABLE_IOS(10_0);

NS_CLASS_AVAILABLE_IOS(2_0) @interface UITextField : UIControl 

@property(nullable, nonatomic,copy)   NSString               *text;                 // default is nil
@property(nullable, nonatomic,copy)   NSAttributedString     *attributedText NS_AVAILABLE_IOS(6_0); // default is nil
@property(nullable, nonatomic,strong) UIColor                *textColor;            // default is nil. use opaque black
@property(nullable, nonatomic,strong) UIFont                 *font;                 // default is nil. use system font 12 pt
@property(nonatomic)        NSTextAlignment         textAlignment;        // default is NSLeftTextAlignment
@property(nonatomic)        UITextBorderStyle       borderStyle;          // default is UITextBorderStyleNone. If set to UITextBorderStyleRoundedRect, custom background images are ignored.
@property(nonatomic,copy)   NSDictionary           *defaultTextAttributes NS_AVAILABLE_IOS(7_0); // applies attributes to the full range of text. Unset attributes act like default values.

@property(nullable, nonatomic,copy)   NSString               *placeholder;          // default is nil. string is drawn 70% gray
@property(nullable, nonatomic,copy)   NSAttributedString     *attributedPlaceholder NS_AVAILABLE_IOS(6_0); // default is nil
@property(nonatomic)        BOOL                    clearsOnBeginEditing; // default is NO which moves cursor to location clicked. if YES, all text cleared
@property(nonatomic)        BOOL                    adjustsFontSizeToFitWidth; // default is NO. if YES, text will shrink to minFontSize along baseline
@property(nonatomic)        CGFloat                 minimumFontSize;      // default is 0.0. actual min may be pinned to something readable. used if adjustsFontSizeToFitWidth is YES
@property(nullable, nonatomic,weak)   id delegate;             // default is nil. weak reference
@property(nullable, nonatomic,strong) UIImage                *background;           // default is nil. draw in border rect. image should be stretchable
@property(nullable, nonatomic,strong) UIImage                *disabledBackground;   // default is nil. ignored if background not set. image should be stretchable

@property(nonatomic,readonly,getter=isEditing) BOOL editing;
@property(nonatomic) BOOL allowsEditingTextAttributes NS_AVAILABLE_IOS(6_0); // default is NO. allows editing text attributes with style operations and pasting rich text
@property(nullable, nonatomic,copy) NSDictionary *typingAttributes NS_AVAILABLE_IOS(6_0); // automatically resets when the selection changes

// You can supply custom views which are displayed at the left or right
// sides of the text field. Uses for such views could be to show an icon or
// a button to operate on the text in the field in an application-defined
// manner.
// 
// A very common use is to display a clear button on the right side of the
// text field, and a standard clear button is provided.

@property(nonatomic)        UITextFieldViewMode  clearButtonMode; // sets when the clear button shows up. default is UITextFieldViewModeNever

@property(nullable, nonatomic,strong) UIView              *leftView;        // e.g. magnifying glass
@property(nonatomic)        UITextFieldViewMode  leftViewMode;    // sets when the left view shows up. default is UITextFieldViewModeNever

@property(nullable, nonatomic,strong) UIView              *rightView;       // e.g. bookmarks button
@property(nonatomic)        UITextFieldViewMode  rightViewMode;   // sets when the right view shows up. default is UITextFieldViewModeNever

// drawing and positioning overrides

- (CGRect)borderRectForBounds:(CGRect)bounds;
- (CGRect)textRectForBounds:(CGRect)bounds;
- (CGRect)placeholderRectForBounds:(CGRect)bounds;
- (CGRect)editingRectForBounds:(CGRect)bounds;
- (CGRect)clearButtonRectForBounds:(CGRect)bounds;
- (CGRect)leftViewRectForBounds:(CGRect)bounds;
- (CGRect)rightViewRectForBounds:(CGRect)bounds;

- (void)drawTextInRect:(CGRect)rect;
- (void)drawPlaceholderInRect:(CGRect)rect;

// Presented when object becomes first responder.  If set to nil, reverts to following responder chain.  If
// set while first responder, will not take effect until reloadInputViews is called.
@property (nullable, readwrite, strong) UIView *inputView;             
@property (nullable, readwrite, strong) UIView *inputAccessoryView;

@property(nonatomic) BOOL clearsOnInsertion NS_AVAILABLE_IOS(6_0); // defaults to NO. if YES, the selection UI is hidden, and inserting text will replace the contents of the field. changing the selection will automatically set this to NO.

@end

@interface UIView (UITextField)
- (BOOL)endEditing:(BOOL)force;    // use to make the view or any subview that is the first responder resign (optionally force)
@end

@protocol UITextFieldDelegate 

@optional

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField;        // return NO to disallow editing.
- (void)textFieldDidBeginEditing:(UITextField *)textField;           // became first responder
- (BOOL)textFieldShouldEndEditing:(UITextField *)textField;          // return YES to allow editing to stop and to resign first responder status. NO to disallow the editing session to end
- (void)textFieldDidEndEditing:(UITextField *)textField;             // may be called if forced even if shouldEndEditing returns NO (e.g. view removed from window) or endEditing:YES called
- (void)textFieldDidEndEditing:(UITextField *)textField reason:(UITextFieldDidEndEditingReason)reason NS_AVAILABLE_IOS(10_0); // if implemented, called in place of textFieldDidEndEditing:

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string;   // return NO to not change text

- (BOOL)textFieldShouldClear:(UITextField *)textField;               // called when clear button pressed. return NO to ignore (no notifications)
- (BOOL)textFieldShouldReturn:(UITextField *)textField;              // called when 'return' key pressed. return NO to ignore.

@end

UIKIT_EXTERN NSNotificationName const UITextFieldTextDidBeginEditingNotification;
UIKIT_EXTERN NSNotificationName const UITextFieldTextDidEndEditingNotification;
UIKIT_EXTERN NSNotificationName const UITextFieldTextDidChangeNotification;

UIKIT_EXTERN NSString *const UITextFieldDidEndEditingReasonKey NS_AVAILABLE_IOS(10_0);

NS_ASSUME_NONNULL_END

  从这个文件中,我们可以看到,这里面有三个通知,还有很多的属性和方法可供大家选择,我们会慢慢的和大家说这些方法的使用规则,并采取代码和效果图的方式展示给大家,争取图文并茂,简单易懂。

这里改变占位文字的位置,其实就是重写方法

- (CGRect)placeholderRectForBounds:(CGRect)bounds;

下面还是直接看代码

#import "JJTextField.h"

@implementation JJTextField

//更改占位文字在文本框中的位置

- (CGRect)placeholderRectForBounds:(CGRect)bounds
{
    return CGRectMake(bounds.origin.x + 30, bounds.origin.y, bounds.size.width, bounds.size.height);
}

@end

我这里是将x向右偏移了30个点,下面看效果图

UITextField自定义使用(一)_第6张图片
效果图

后记

  大家有没有觉得UITextField很好玩了呢,慢慢的我会给大家把他所有的用法都讲出来,今天有事就先写这么多吧,未完,待续~~~~

UITextField自定义使用(一)_第7张图片
看着就好舒服

你可能感兴趣的:(UITextField自定义使用(一))