Custom input box for iOS development (using UITextField and UITextView) to customize uitextfield

Source: Internet
Author: User

Custom input box for iOS development (using UITextField and UITextView) to customize uitextfield

Recently, some input boxes are often customized during project creation. We will share them here today.

My idea is to inherit from the control of the system and then use drawRect to redraw the control.

So how does drawRect work?

Working principle of drawRect:
First of all, Apple does not recommend that we directly use drawRect for work, and direct calls to it do not have any effect. Apple asked us to call the setNeedsDisplay method in the UIView class, then the program will automatically call the drawRect Method for re-painting. (Call setNeedsDisplay will automatically call drawRect ).

In UIView, override the drawRect: (CGRect) aRect method to define the pattern you want to draw. in general, this method will only be painted once. that is to say, this drawRect method is generally called only once.
In some cases, to manually redraw this View, you only need to use the [self setNeedsDisplay] method.
DrawRect is called after the Controller-> loadView, Controller-> viewDidLoad method is called. so don't worry about the drawRect of these views in the controller. in this way, you can set some values for the View in the Controller (if some variable values are required for the View draw ).

 

1. If the rect size is not set during UIView initialization, The drawRect will not be automatically called.
2. This method is called after sizeThatFits is called. Therefore, you can call sizeToFit to calculate the size. Then the system automatically calls drawRect: method.
3. Set the value of contentMode to UIViewContentModeRedraw. The drawRect: is automatically called every time the frame is set or changed :.
4. Call setNeedsDisplay directly or setNeedsDisplayInRect to trigger drawRect:, but there is a precondition that the rect cannot be 0.
1, 2 and 3 are not recommended.

 

1. The input box that can be input in multiple rows (inherited from UITextView, the effect is as follows)

# Pragma mark -- call at initialization --- (instancetype) initWithFrame :( CGRect) frame {if (self = [super initWithFrame: frame]) {/*** set the default value for the attribute during initialization */self. placeholder = @ "Enter Text"; self. placeholderColor = [UIColor lightGrayColor]; self. placeholderFont = [UIFont systemFontOfSize: 14];/*** use textVeiw to add notifications. When textView changes, the textChanged method is called */[[nsicationicationcenter defacenter center] addObserver: self selector: @ selector (textChanged :) name: UITextViewTextDidChangeNotification object: nil];} return self ;}# pragma mark -- redraw (add placeholder to textVeiw) --- (void) drawRect :( CGRect) rect {// if the text disappears, the placeholder if (self. text. length = 0) {CGRect placeholderRect = CGRectZero; placeholderRect. origin. x = 10; placeholderRect. origin. y = 5; placeholderRect. size. width = self. frame. size. width-10; placeholderRect. size. height = self. frame. size. height-5; [self. placeholder drawInRect: placeholderRect withAttributes :@{ NSFontAttributeName: _ placeholderFont, Region: _ placeholderColor}];} [super drawRect: rect];} # pragma mark -- this method is called when the text changes-(void) textChanged :( NSNotification *) notification {/*** re-paint when text changes */[self setNeedsDisplay];} # pragma mark -- remove notification-(void) dealloc {[[NSNotificationCenter defacenter center] removeObserver: self];}

If you want to customize more feature-based attributes, you can add more attributes to the attribute !!!

2. Customize the qualified input box (inherited from UITextField, the effect is as follows)

 

In the left view above, there are only two rounded corners and 1px spacing between the top and bottom left, And the placeholder is on the right.

-(Instancetype) initWithFrame :( CGRect) frame {if (self = [super initWithFrame: frame]) {/*** initialize the attribute and set the default value */_ placeholderFont = [UIFont systemFontOfSize: 16]; _ placeholderColor = [UIColor lightGrayColor]; CGFloat height = frame. size. height; UIView * leftView = [[UIView alloc] initWithFrame: CGRectMake (0, 1, height-1, height-2)]; leftView. backgroundColor = [UIColor redColor]; UIImageView * imageView = [[UIImageView alloc] initWithImage: [UIImage imageNamed: @ "Icon"]; imageView. frame = CGRectMake (0, 0, height-1, height-2); [leftView addSubview: imageView]; // This method can be used to make the Left view only have two rounded corners: UIBezierPath * maskPath = [UIBezierPath bezierPathWithRoundedRect: leftView. bounds byRoundingCorners: UIRectCornerBottomLeft | UIRectCornerTopLeft cornerRadii: CGSizeMake (5, 5)]; CAShapeLayer * maskLayer = [[CAShapeLayer alloc] init]; maskLayer. frame = leftView. bounds; maskLayer. path = maskPath. CGPath; leftView. layer. mask = maskLayer; self. leftView = leftView; self. leftViewMode = UITextFieldViewModeAlways; NSLog (@ "% s" ,__ func _);} return self ;}// I do not know the usage of these two methods, if you know anything, contact me and tell me/* # pragma mark -- reset the border area-(CGRect) borderRectForBounds :( CGRect) bounds {CGRect borderRect = [super borderRectForBounds: bounds]; return borderRect;} # pragma mark -- reset text area-(CGRect) textRectForBounds :( CGRect) bounds {CGRect textRect = [super textRectForBounds: bounds]; return textRect ;} */# pragma mark -- reset placeholder-(CGRect) placeholderRectForBounds :( CGRect) bounds {CGRect placeholderRect = [super placeholderRectForBounds: bounds]; /*** place the placeholder on the right */CGFloat placeholderWidth = [self. placeholder boundingRectWithSize: CGSizeMake (MAXFLOAT, MAXFLOAT) options: NSStringDrawingUsesLineFragmentOrigin attributes: @ {NSFontAttributeName: _ placeholderFont} context: nil]. size. width; placeholderRect. origin. x + = placeholderRect. size. width-placeholderWidth-5; return placeholderRect;} # pragma mark -- reset edit region-(CGRect) reset :( CGRect) bounds {CGRect editingRect = [super editingRectForBounds: bounds]; return editingRect ;} # pragma mark -- reset delete button area-(CGRect) clearButtonRectForBounds :( CGRect) bounds {CGRect clearButtonRect = [super clearButtonRectForBounds: bounds]; return clearButtonRect ;} # pragma mark -- reset the Left view area-(CGRect) leftViewRectForBounds :( CGRect) bounds {CGRect leftViewRect = [super leftViewRectForBounds: bounds]; leftViewRect. origin. x + = 1; return leftViewRect;} # pragma mark -- reset the right view area-(CGRect) reset :( CGRect) bounds {CGRect rightViewRect = [super rightViewRectForBounds: bounds]; return rightViewRect;} # pragma mark -- redraw text (called after this method becomes the first responder)-(void) drawTextInRect :( CGRect) rect {[super drawTextInRect: rect]; self. textColor = [UIColor purpleColor];} # pragma mark -- Repaint placeholder

// During the first display, the placeholderRectForBounds method is called first, and then the method is called.

// When it is displayed later, it is called after the placeholderRectForBounds: method is called, and then the placeholderRectForBounds: method is called, this will offset the position of the placeholder (it will not be centered when it becomes the first responder. If you know how to solve this problem, please contact me. Thank you !!!)
-(Void) reset :( CGRect) rect {[super drawPlaceholderInRect: rect];/*** call kvo to modify the _ placeholderLabel attribute of the system */[self setValue: _ placeholderColor forKeyPath: @ "_ placeholderLabel. textColor "]; [self setValue: _ placeholderFont forKeyPath: @" _ placeholderLabel. font "];}

If you need this demo, you can download it from my space or add qq: 357898849 for a chat !!!

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.