Do you really know UITextView ?, UITextView

Source: Internet
Author: User

Do you really know UITextView ?, UITextView

I. First, let's take a look at the definition of UITextView.

Define (2_0) @ interface UITextView: UIScrollView <UITextInput> @ property (nullable, nonatomic, weak) id <strong> delegate; @ property (null_resettable, nonatomic, copy) NSString * text; @ property (nullable, nonatomic, strong) UIFont * font; @ property (nullabel, nonatomic, strong) UIColor * textColor; @ property (nonatomic) NSTextAlignment textAlignment; @ property (nonatomic) nsange selectedRange; // Selection Range: @ property (nonatomic, getter = isEditable) BOOL editable; // can you edit @ property (nonatomic, getter = isSelectable) BOOL selectable NS_AVAILABLE_IOS (7_0 ); // whether @ property (nonatomic) UIDataDetectorTypes dataDetectorTypes NS_AVAILABLE_IOS (3_0) can be selected ); // attributes can be set to convert the phone number, website address, email, and formatted text into link text @ property (nonatomic) BOOL allowsEditingTextAttributes NS_AVAILABLE_IOS (6_0 ); // The default value is NO. Whether to change the character attribute dictionary @ property (null_resettable, copy) NSAttributedString * attributedText NS_AVAILABLE_IOS (6_0); // Rich Text @ property (nonatomic, copy) NSDictionary <NSString *, id> * typingAttributes NS_AVAILABLE_IOS (6_0); // scroll to a paragraph in the text-(void) scrollRangeToVisible :( nsange) range; @ property (nullable, readwrite, strong) UIView * inputView; @ property (nullable, readwrite, strong) UIView * inputAccessoryView; @ property (nonatomic) BOOL clearsOnInsertion NS_AVAILABLE_IOS (6_0 ); // set whether to allow the content to be inserted in the middle of the Content During reedit-(instancetype) initWithFrame :( CGRect) frame textContainer :( nullable NSTextContainer *) textContainer partition (7_0) partition) initWithCoder :( NSCoder *) aDecoder NS_DESIGNATED_INITIALIZER; // defines a rectangular area for storing the text that has been typeset and set attributes @ property (nonatomic, readonly) NSTextContainer * textContainer layout (7_0); @ property (nonatomic, assign) UIEdgeInsets textContainerInset layout (7_0); // used to manage the layout of text content in NSTextStorage @ property (nonatomic, readonly) NSLayoutManager * layoutManager NS_AVAILABLE_IOS (7_0); // NSTextStorage saves and manages the text to be displayed in UITextView, which is a subclass of NSMutableAttributedString, since the attribute @ property (nonatomic, readonly, strong) NSTextStorage * textStorage NS_AVAILABLE_IOS (7_0) can be flexibly added to or modified to the text, // The style setting of the link text @ property (null_resettable, nonatomic, copy) NSDictionary <NSString *, id> * linkTextAttributes NS_AVAILABLE_IOS (7_0); @ end

UITextView inherits from UIScrollView and complies with the UITextInput protocol. UIScrollView inherits from UIView and follows the NSCoding protocol. The preceding attributes are the same as those of UITextField and are not marked; for the UITextInput protocol, see the content in UITextField. It contains some knowledge about keyboard response and corresponding notification processing;

Knowledge Point 1: About UIDataDetectorTypes this attribute can be set to convert text such as phone number, website address, email, and date in the correct format into link text

typedef NS_OPTIONS(NSUInteger, UIDataDetectorTypes) {    UIDataDetectorTypePhoneNumber                              = 1 << 0,          // Phone number detection    UIDataDetectorTypeLink                                     = 1 << 1,          // URL detection    UIDataDetectorTypeAddress NS_ENUM_AVAILABLE_IOS(4_0)       = 1 << 2,          // Street address detection    UIDataDetectorTypeCalendarEvent NS_ENUM_AVAILABLE_IOS(4_0) = 1 << 3,          // Event detection    UIDataDetectorTypeNone          = 0,               // No detection at all    UIDataDetectorTypeAll           = NSUIntegerMax    // All types};
Example: textView. dataDetectorTypes = UIDataDetectorTypeAll; UIDataDetectorTypeAll can detect the phone number, website address, and email address. The content in the qualified text is highlighted;

Knowledge Point 2: Use instances to set link styles

UITextView * textView = [[UITextView alloc] initWithFrame: CGRectMake (0,100,300, 50)]; optional * attributedString = [[NSMutableAttributedString alloc] initWithString: @ "this is a link: www.123456.com"]; [attributedString addattriename: NSLinkAttributeName value: @ "url1: // www.baidu.com" range: NSMakeRange (7, 14)]; NSDictionary * linkAttributes =@{ tags: [UIColor greenColor], Region: [UIColor lightGrayColor], NSUnderlineStyleAttributeName: @ (NSUnderlinePatternSolid)}; textView. linkTextAttributes = linkAttributes; textView. attributedText = attributedString; textView. delegate = self; textView. editable = NO; // you cannot click the link [self. view addSubview: textView];
// Implement proxy-(BOOL) textView :( UITextView *) textView shouldInteractWithURL :( NSURL *) URL inRange :( nsange) characterRange {if ([URL scheme] isw.tostring: @ "url1"]) {NSString * url = [URL host]; NSLog (@ "% @", url ); // use the url here to do something ...... return NO;} return YES ;}

Knowledge Point 3: UITextView: responds to the return event of the keyboard

-(BOOL) textView :( UITextView *) textView shouldChangeTextInRange :( nsange) range replacementText :( NSString *) text {if ([text isEqualToString: @ "\ n"]) {// determine whether the entered word is a carriage return, that is, press return // here to make the code for your response to the return key [textView resignFirstResponder]; return NO; // NO is returned here, it indicates that the return key value is invalid, that is, when the return key is pressed on the page, no line breaks will appear. If yes, the input page will wrap.} return YES ;}

Knowledge Point 4: How to elegantly change the height of UITextView in real time based on input text

// Initialize the control self. contentTextView = [[UITextView alloc] initWithFrame: CGRectMake (kMainBoundsWidth-250)/2, kMainBoundsHeight/2-50,250, 39)]; self. contentTextView. layer. cornerRadius = 4; self. contentTextView. layer. masksToBounds = YES; self. contentTextView. delegate = self; self. contentTextView. layer. borderWidth = 1; self. contentTextView. font = [UIFont systemFontOfSize: 14]; self. contentTextView. layer. borderColor = [[UIColor lightGrayColor] colorWithAlphaComponent: 0.4] CGColor]; // Add the following sentence to adjust the cursor position, let the cursor appear in the middle of UITextView self. contentTextView. textContainerInset = UIEdgeInsetsMake (10, 0, 0, 0); [self. view addSubview: self. contentTextView];
// Calculate the input text height. The returned height value is 22 because UITextView has an initial height value of 40. However, when you enter the first line of text, the text height is only 18, therefore, the height of UITextView will change, and the effect is not very good-(float) heightForTextView: (UITextView *) textView WithText: (NSString *) strText {CGSize constraint = CGSizeMake (textView. contentSize. width, CGFLOAT_MAX); CGRect size = [strText boundingRectWithSize: constraint options :( optional | attributes) attributes: @ {NSFontAttributeName: [UIFont systemFontOfSize: 14]} context: nil]; float textHeight = size. size. height + 22.0; return textHeight ;}
// Call this method after each text input. The input text is not in textView. text, and in another parameter text, after this method is completed, the text entered each time is added to textView. text. The solution is to set textView. text and text are spliced-(BOOL) textView :( UITextView *) textView shouldChangeTextInRange :( nsange) range replacementText :( NSString *) text {CGRect frame = textView. frame; float height; if ([text isEqual: @ ""]) {if (! [TextView. text isEqualToString: @ ""]) {height = [self heightForTextView: textView WithText: [textView. text substringToIndex: [textView. text length]-1];} else {height = [self heightForTextView: textView WithText: textView. text] ;}} else {height = [self heightForTextView: textView WithText: [NSString stringWithFormat: @ "%", textView. text, text];} frame. size. height = height; [UIView animateWithDuration: 0.5 animations: ^ {textView. frame = frame;} completion: nil]; return YES ;}

Knowledge Point 5: textView does not actually have PlaceHolder. How to Set PlaceHolder is as follows:

#import <UIKit/UIKit.h>@interface UIPlaceHolderTextView : UITextView@property (nonatomic, strong) NSString *placeholder;@property (nonatomic, strong) UIColor *placeholderColor;-(void)textChanged:(NSNotification*)notification;@end
#import "UIPlaceHolderTextView.h"@interface UIPlaceHolderTextView()@property (nonatomic, strong) UILabel *placeHolderLabel;@end@implementation UIPlaceHolderTextViewCGFloat const UI_PLACEHOLDER_TEXT_CHANGED_ANIMATION_DURATION = 0.25;- (void)dealloc{    [[NSNotificationCenter defaultCenter] removeObserver:self];#if __has_feature(objc_arc)#else    [_placeHolderLabel release]; _placeHolderLabel = nil;    [_placeholderColor release]; _placeholderColor = nil;    [_placeholder release]; _placeholder = nil;    [super dealloc];#endif}- (void)awakeFromNib{    [super awakeFromNib];    if (!self.placeholder) {        _placeholder = @"";    }        if (!self.placeholderColor) {        [self setPlaceholderColor:[UIColor lightGrayColor]];    }        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textChanged:) name:UITextViewTextDidChangeNotification object:nil];}- (id)initWithFrame:(CGRect)frame{    if( (self = [super initWithFrame:frame]) )    {        _placeholder = @"";        [self setPlaceholderColor:[UIColor lightGrayColor]];        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textChanged:) name:UITextViewTextDidChangeNotification object:nil];    }    return self;}- (void)textChanged:(NSNotification *)notification{    if([[self placeholder] length] == 0)    {        return;    }        [UIView animateWithDuration:UI_PLACEHOLDER_TEXT_CHANGED_ANIMATION_DURATION animations:^{        if([[self text] length] == 0)        {            [[self viewWithTag:999] setAlpha:1];        }        else        {            [[self viewWithTag:999] setAlpha:0];        }    }];}- (void)setText:(NSString *)text {    [super setText:text];    [self textChanged:nil];}- (void)drawRect:(CGRect)rect{    if( [[self placeholder] length] > 0 )    {        UIEdgeInsets insets = self.textContainerInset;        if (_placeHolderLabel == nil )        {                        _placeHolderLabel = [[UILabel alloc] initWithFrame:CGRectMake(insets.left+5,insets.top,self.bounds.size.width - (insets.left +insets.right+10),1.0)];            _placeHolderLabel.lineBreakMode = NSLineBreakByWordWrapping;            _placeHolderLabel.font = self.font;            _placeHolderLabel.backgroundColor = [UIColor clearColor];            _placeHolderLabel.textColor = self.placeholderColor;            _placeHolderLabel.alpha = 0;            _placeHolderLabel.tag = 999;            [self addSubview:_placeHolderLabel];        }        _placeHolderLabel.text = self.placeholder;        [_placeHolderLabel sizeToFit];        [_placeHolderLabel setFrame:CGRectMake(insets.left+5,insets.top,self.bounds.size.width - (insets.left +insets.right+10),CGRectGetHeight(_placeHolderLabel.frame))];        [self sendSubviewToBack:_placeHolderLabel];    }        if( [[self text] length] == 0 && [[self placeholder] length] > 0 )    {        [[self viewWithTag:999] setAlpha:1];    }        [super drawRect:rect];}- (void)setPlaceholder:(NSString *)placeholder{    if (_placeholder != placeholder) {        _placeholder = placeholder;        [self setNeedsDisplay];    }    }@end

Ii. Proxy Method Content

@ Protocol UITextViewDelegate <NSObject, comment> @ optional // The textView to be edited-(BOOL) finished :( UITextView *) textView; // The textViewShouldEndEditing :( UITextView *) textView; // start editing-(void) textViewDidBeginEditing :( UITextView *) textView; // end editing-(void) textViewDidEndEditing :( UITextView *) textView; // The text will be changed-(BOOL) textView :( UITextView *) textView shouldChangeTextInRange :( nsange) range replacementText :( NSString *) text; // The text is changed-(void) textViewDidChange :( UITextView *) textView; // The focus changes-(void) textViewDidChangeSelection :( UITextView *) textView; // whether the URL in the text can be operated-(BOOL) textView :( UITextView *) textView shouldInteractWithURL :( NSURL *) URL inRange :( nsange) characterRange NS_AVAILABLE_IOS (7_0); // whether to allow operations on Rich Text in text-(BOOL) textView :( UITextView *) textView shouldInteractWithTextAttachment :( NSTextAttachment *) textAttachment inRange :( nsange) characterRange NS_AVAILABLE_IOS (7_0 );

 

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.