文本处理(UILabel、 UITextField、UITextView、富文本、emoji、IQKeyboardManager、UIFont、UIColor)之iOS笔记摘录

目录

    1. UILabel  文本展示
    2. UITextField    文本编辑框(单行)
    3. UITextView     文本编辑框(多行)
    4. NSMutableAttributedString  复杂文本(富文本)
    5. emoji 
    6. 第三方键盘IQKeyboardManager
    7. UIFont
    8. UIColor

前言


1. UILabel 文本控件( : UIView)

// 创建label
UILabel *textLabel=[UILabel new];
[self.view addSubview:textLabel];
[textLabel autoPinEdgesToSuperviewEdgesWithInsets:UIEdgeInsetsZero];

常用

文本、字体、颜色、对齐方式、行数、省略模式

    // 设置 文本 
    [textLabel setText:@""];
    // 设置 复杂文本
    [textLabel setAttributedText:[NSAttributedString new]];
    // 设置 字体
    [textLabel setFont:[UIFont systemFontOfSize:16]];
    // 设置 颜色
    [textLabel setTextColor:[UIColor colorWithWhite:0.35 alpha:1]];
    // 设置 对齐方式(左 右 居中)
    [textLabel setTextAlignment:NSTextAlignmentLeft];
    /
       NSTextAlignmentLeft
       NSTextAlignmentRight
       NSTextAlignmentCenter
    /
    // 设置 行数(默认:1 ,0:则无限行)
    [textLabel setNumberOfLines:0];
    // 设置 省略mode(文本超范围时)
    [textLabel setLineBreakMode:NSLineBreakByClipping];
    /
       ByWordWrapping         以单词为显示单位显示(后面部分不显示)(默认)
       ByCharWrapping         以字符为显示单位显示(后面部分不显示)
       ByClipping             剪切与控件宽度相同的内容长度(后半部分被删除)
       ByTruncatingHead       前面以…省略,尾部正常显示
       ByTruncatingTail       尾部以…省略,头部正常显示(常用)
       ByTruncatingMiddle     中间以…省略,头尾正常显示
     /
缩放

  // 是否根据文本内容和控件大小来改变字体大小(默认:false)
  [textLabel setAdjustsFontSizeToFitWidth:true];
  // 最小缩放系数
  [textLabel setMinimumScaleFactor:6.0];
可交互

    // UILabel 和 UIImageView等少数控件,其userInteractionEnabled属性默认为false(即不可交互)
    // 设置 是否允许交互
    [textLabel setUserInteractionEnabled:true];

    // 设置 是否禁用控件 , 
    [textLabel setEnabled:true];
去除str两端的空格
  [str stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];

对URL百分号编码(标点符号/中文->百分号)
  [str stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
移除百分号编码
  [str stringByRemovingPercentEncoding];
str->data
  NSData *data=[@"" dataUsingEncoding:NSUnicodeStringEncoding];
data->str
  NSStringEncoding enc = CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000);
  NSString *str=[[NSString alloc] initWithData:data encoding:enc];
  // 
  NSString *str2=[[NSString alloc] initWithData:data encoding:NSUnicodeStringEncoding]; // NSUTF8StringEncoding

文本自适应

// 获取高度/宽度

CGRect contentRect=[@"hello" boundingRectWithSize:CGSizeMake(kScreenWidth-kMagrin15*2, 15) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:kPingFangMediumFont(kFontNum11)} context:nil];

// 获取text高度 方式2

[self.contentLabel textRectForBounds:CGRectMake(100, 5, RZSCREENWIDTH-120, 500) limitedToNumberOfLines:0];

// 获取text高度 方式3

CGSize contentSize = [self.contentLabel sizeThatFits:CGSizeMake(100, MAXFLOAT)];

键盘显示/隐藏通知

    // 键盘显示/隐藏通知
    UIKeyboardWillShowNotification          // 键盘即将显示
    UIKeyboardDidShowNotification           // 键盘已经显示
    UIKeyboardWillHideNotification          // 键盘即将隐藏
    UIKeyboardDidHideNotification           // 键盘已经隐藏
    /*
    UIKeyboardFrameBeginUserInfoKey         // NSValue of CGRect
    UIKeyboardFrameEndUserInfoKey           // NSValue of CGRect  键盘显示后
    UIKeyboardAnimationDurationUserInfoKey  // NSNumber of double 动画时长
    UIKeyboardAnimationCurveUserInfoKey     // NSNumber of NSUInteger (UIViewAnimationCurve)
    UIKeyboardIsLocalUserInfoKey            // NSNumber of BOOL 
    // 举例:获取键盘的高度
    NSDictionary *userInfo = [aNotification userInfo];
    NSValue *aValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGRect keyboardRect = [aValue CGRectValue];
    int height = keyboardRect.size.height;
    */

    // 键盘frame改变通知
    UIKeyboardWillChangeFrameNotification
    UIKeyboardDidChangeFrameNotification
    /*
    UIKeyboardCenterBeginUserInfoKey
    UIKeyboardCenterEndUserInfoKey
    UIKeyboardBoundsUserInfoKey
    */

2. UITextField 文本输入框(: UIControl)

UITextField *contentTF=[UITextField new];
[self.view addSubview:contentTF];
[contentTF autoPinEdgesToSuperviewEdgesWithInsets:UIEdgeInsetsZero];

常用

    // 设置 文本、富文本
    [contentTF setText:@""];
    [contentTF setAttributedText:[[NSAttributedString alloc]initWithString:@"" attributes:@{
    }]];
    // 设置 字体
    [contentTF setFont:[UIFont systemFontOfSize:17]];
    // 设置 颜色
    [contentTF setTextColor:[UIColor redColor]];
    // 设置 对齐方式
    [contentTF setTextAlignment:NSTextAlignmentLeft];
    /*
     NSTextAlignmentLeft
     NSTextAlignmentCenter
     NSTextAlignmentRight
     */
    // 设置 提示富文本
    [contentTF setAttributedPlaceholder:[[NSMutableAttributedString alloc]initWithString:@"placeholder" attributes:@{
    }]];
/*
    // 设置 提示文本
    [contentTF setPlaceholder:@""];
    // 前提:必须先设置placeholder
    // 设置 提示文本颜色
    [contentTF setValue:[UIColor darkGrayColor] forKeyPath:@"_placeholderLabel.textColor"];
    // 设置 提示文本字体
    [contentTF setValue:[UIFont systemFontOfSize:14] forKeyPath:@"_placeholderLabel.font"];
*/
    // 设置 是否加密显示
    [contentTF setSecureTextEntry:true];
    // 获得焦点(成为第一响应者)
    [contentTF becomeFirstResponder];
    // 失去焦点(注销第一响应者)
    //(只能隐藏自己的键盘,不能隐藏其他textF的键盘)
    [contentTF resignFirstResponder];
    // 结束所有编辑状态(隐藏所有键盘)
    [self.view endEditing:true];

    // 内容改变后回调
    [contentTF addTarget:self action:@selector(textfieldContentChange:) forControlEvents:UIControlEventEditingChanged];
    //-------------- 右侧x视图 --------------
    // 设置 右侧x视图Mode
    [contentTF setClearButtonMode:UITextFieldViewModeAlways];
    /*
     UITextFieldViewModeNever,              从不显示
     UITextFieldViewModeWhileEditing,       仅编辑时
     UITextFieldViewModeUnlessEditing,      除了编辑
     UITextFieldViewModeAlways              一直显示
     */
    // 设置 是否插入文本时清空数据
    [contentTF setClearsOnInsertion:true];
    //-------------- 两侧视图 --------------
    // 设置 左侧视图mode
    [contentTF setLeftViewMode:UITextFieldViewModeAlways];
    /*
     UITextFieldViewModeNever,              从不显示
     UITextFieldViewModeWhileEditing,       仅编辑时
     UITextFieldViewModeUnlessEditing,      除了编辑
     UITextFieldViewModeAlways              一直显示
     */
    // 设置 左侧视图
    [contentTF setLeftView:[UIView new]];
    // 设置 右侧视图mode、右侧视图
    // 右视图会覆盖x清空按钮
    [contentTF setRightViewMode:UITextFieldViewModeAlways];
    [contentTF setRightView:[UIView new]];
    //-------------- 键盘 --------------
    // 设置 键盘Mode
    [contentTF setKeyboardType:UIKeyboardTypeNumberPad];
    /*
     UIKeyboardTypeDefault                  默认的 键盘
     UIKeyboardTypeASCIICapable             纯英文字母的 键盘
     UIKeyboardTypeNumbersAndPunctuation    数字和标点的 键盘
     UIKeyboardTypeURL                      便于输入数字的 键盘 (.com)
     UIKeyboardTypeNumberPad                便于输入数字的 键盘(纯数字)
     UIKeyboardTypePhonePad                 便于拨号呼叫的 键盘(手机号)
     UIKeyboardTypeNamePhonePad             便于聊天拨号的 键盘
     UIKeyboardTypeEmailAddress             便于输入Email的 键盘 (@)
     UIKeyboardTypeDecimalPad               用于输入数字和【小数点】的 键盘
     UIKeyboardTypeTwitter                  便于在网页上书写的 键盘
     UIKeyboardTypeWebSearch
     UIKeyboardTypeASCIICapableNumberPad
     UIKeyboardTypeAlphabet
     */
    // 设置 自定义键盘View
    [contentTF setInputView:[UIView new]];
    // 设置 自定义键盘上方View
    [contentTF setInputAccessoryView:[UIView new]];
    // 设置键盘右上角return按钮标题
    [contentTF setReturnKeyType:UIReturnKeyDone];
    /*
     UIReturnKeyDefault,    完成
     UIReturnKeyGo,         完成并跳到另一页
     UIReturnKeyGoogle,     搜索
     UIReturnKeyJoin,       注册用户或添加数据
     UIReturnKeyNext,       继续下一步
     UIReturnKeyRoute,      发送
     UIReturnKeySearch,
     UIReturnKeySend,
     UIReturnKeyYahoo,
     UIReturnKeyDone,
     UIReturnKeyEmergencyCall,
     UIReturnKeyContinue
     */
    // 设置 键盘外观
    [contentTF setKeyboardAppearance:UIKeyboardAppearanceDark];
    /*
     UIKeyboardAppearanceDefault,   浅灰色(默认颜色)
     UIKeyboardAppearanceDark       黑色
     UIKeyboardAppearanceLight      亮色,与Default很相似
     UIKeyboardAppearanceAlert
     */
    //-------------- rect --------------
    CGRect rect=[contentTF borderRectForBounds:contentTF.bounds];
    CGRect rect2=[contentTF textRectForBounds:contentTF.bounds];
    CGRect rect3=[contentTF placeholderRectForBounds:contentTF.bounds];
    CGRect rect4=[contentTF editingRectForBounds:contentTF.bounds];
    CGRect rect5=[contentTF clearButtonRectForBounds:contentTF.bounds];
    CGRect rect6=[contentTF leftViewRectForBounds:contentTF.bounds];
    CGRect rect7=[contentTF rightViewRectForBounds:contentTF.bounds];
    //-------------- 其他 --------------
    // 设置边框Mode
    [contentTF setBorderStyle:UITextBorderStyleNone];
    /*
     UITextBorderStyleNone,         无边框
     UITextBorderStyleLine,         直线
     UITextBorderStyleBezel,        边线+阴影
     UITextBorderStyleRoundedRect   圆角    (默认白色背景,此时背景图无效)
     */
    // 设置 背景色、背景图片
    [contentTF setBackgroundColor:[UIColor blueColor]];
    [contentTF setBackground:[UIImage imageNamed:@""]]; // 边框样式需为none
    [contentTF setDisabledBackground:[UIImage imageNamed:@""]];
    // 设置 内容纵向对齐方式
    [contentTF setContentVerticalAlignment:UIControlContentVerticalAlignmentTop];
    /*
     UIControlContentVerticalAlignmentCenter
     UIControlContentVerticalAlignmentTop
     UIControlContentVerticalAlignmentBottom
     UIControlContentVerticalAlignmentFill
     */
    // 设置 内容横向对齐方式
    [contentTF setContentHorizontalAlignment:UIControlContentHorizontalAlignmentLeft];
    /*
     UIControlContentHorizontalAlignmentCenter
     UIControlContentHorizontalAlignmentLeft
     UIControlContentHorizontalAlignmentRight
     UIControlContentHorizontalAlignmentFill
     UIControlContentHorizontalAlignmentLeading
     UIControlContentHorizontalAlignmentTrailing
     */
    // 设置 是否自动补全
    [contentTF setAutocorrectionType:UITextAutocorrectionTypeNo];
    /*
     UITextAutocorrectionTypeDefault,
     UITextAutocorrectionTypeNo,        不自动更正
     UITextAutocorrectionTypeYes,       自动更正
     */
    // 设置 文本随控件缩放
    [contentTF setAdjustsFontSizeToFitWidth:true];
    // 设置 最小缩放字体
    [contentTF setMinimumFontSize:14];

dele

    // 
    [contentTF setDelegate:self];

// 是否允许开始编辑
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField{return true;}
// 开始编辑后调用
- (void)textFieldDidBeginEditing:(UITextField *)textField{}
// 是否允许结束编辑
- (BOOL)textFieldShouldEndEditing:(UITextField *)textField{return true;}
// 结束编辑后调用
- (void)textFieldDidEndEditing:(UITextField *)textField{}
// 是否允许改变
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    // 拿到如果改变后的字符串,判断
    NSString *str=[textField.text stringByReplacingCharactersInRange:range withString:string];
    return true;
}
// 是否允许清除
- (BOOL)textFieldShouldClear:(UITextField *)textField{return true;}
// 是否允许return
- (BOOL)textFieldShouldReturn:(UITextField *)textField{return true;}

notification

// 由textField发出的通知:
    UITextFieldTextDidBeginEditingNotification  
    UITextFieldTextDidEndEditingNotification        
    UITextFieldTextDidChangeNotification            // 用于联想词汇
// 由键盘视图发出的通知:
    UIKeyboardWillShowNotification 即将弹出时 发送
    UIKeyboardDidShowNotification  完成弹出时 发送
    UIKeyboardWillHideNotification 即将隐藏时 发送
    UIKeyboardDidHideNotification  完成隐藏时 发送
    UIKeyboardWillChangeFrameNotification 即将改变frame时 发送
    UIKeyboardDidChangeFrameNotification  完成改变frame时 发送

IQKeyboardManager第三方(方便键盘管理)

    pod 'IQKeyboardManager'

3. UITextView 多行文本(: UIScrollView)

UITextView *contentTV=[UITextView new];
[self.view addSubview:contentTV];

    // 设置 文本
    [contentTV setText:@""];
    // 设置 富文本
    [contentTV setAttributedText:[NSAttributedString new]];
    // 设置 字体
    [contentTV setFont:[UIFont systemFontOfSize:15]];
    // 设置 颜色
    [contentTV setTextColor:[UIColor redColor]];
    // 设置 对齐方式
    [contentTV setTextAlignment:NSTextAlignmentLeft];

    // 设置 是否允许滚动
    [contentTV setScrollEnabled:true];
    // 滚动至指定范围
    [contentTV scrollRangeToVisible:NSMakeRange(0, 10)];

    // 设置 文本是否可选
    [contentTV setSelectable:true];
    // 设置 允许选择的范围
    [contentTV setSelectedRange:NSMakeRange(0, 10)];
    // 设置 文本是否可编辑
    [contentTV setEditable:true];

    // 成为第一响应者
    [contentTV becomeFirstResponder];
    // 注销第一响应者
    [contentTV resignFirstResponder];

    // 自定义 键盘View
    [contentTV setInputView:[UIView new]];
    // 自定义 键盘上方View
    [contentTV setInputAccessoryView:[UIView new]];
    // 设置 frame(基本不用)
    [contentTV setFrame:CGRectZero];
    // 设置 背景色
    [contentTV setBackgroundColor:[UIColor blueColor]];
    // 设置 边框色、边宽宽度
    [contentTV.layer setBorderColor:[UIColor blueColor].CGColor];
    [contentTV.layer setBorderWidth:1.0];
    // 设置 圆角
    [contentTV.layer setCornerRadius:5.0];
    [contentTV.layer setMasksToBounds:true];
    // 判断 输入法是否是中文
    BOOL isChina=[[[contentTV textInputMode] primaryLanguage]isEqualToString: @"en-US"];
    // 获取 选中文本的范围
    UITextRange *selectedRange = [contentTV markedTextRange];
    // 获取 高亮部分
    UITextPosition *position = [contentTV positionFromPosition:selectedRange.start offset:0];

dele

    // dele
    [contentTV setDelegate:self];


// 开始编辑前调用(是否允许开始编辑)
- (BOOL)textViewShouldBeginEditing:(UITextView *)textView{return true;}
// 开始编辑后调用
- (void)textViewDidBeginEditing:(UITextView *)textView{}
// 结束编辑前调用(是否允许结束编辑)
- (BOOL)textViewShouldEndEditing:(UITextView *)textView{return true;}
// 结束编辑后调用
- (void)textViewDidEndEditing:(UITextView *)textView{}
// 编辑内容后调用(是否允许改变)用于控制字符长度
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{ return true;}
// 文本内容改变后调用
- (void)textViewDidChange:(UITextView *)textView{}
// 选中文本变化后调用
- (void)textViewDidChangeSelection:(UITextView *)textView{}

4. NSMutableAttributedString 复杂文本(富文本)

    // 创建(文本Font,文本Color)
    NSMutableAttributedString *muStr=[[NSMutableAttributedString alloc]initWithString:@"" attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:11],NSForegroundColorAttributeName:[UIColor blueColor]}];
    // 追加单个属性(背景色)
    [muStr addAttribute:NSBackgroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(0, 10)];
    // 追加多个属性(下划线)
    [muStr addAttributes:@{NSUnderlineStyleAttributeName:@(2),NSUnderlineColorAttributeName:[UIColor blueColor]} range:NSMakeRange(0, 10)];
    // 字符间距(正数则 加宽),基线偏移(正数则 上偏),字符是否连体(0没有连体字符,1默认的连体字符)
    [muStr setAttributes:@{NSKernAttributeName:@(10),NSBaselineOffsetAttributeName:@(10),NSLigatureAttributeName:@(2)} range:NSMakeRange(0, 10)];


文本字体(默认值:字体:Helvetica(Neue) ,字号:12)
      NSFontAttributeName
文本颜色(默认值:黑色)
      NSForegroundColorAttributeName
背景色(默认值为nil, 透明色)
      NSBackgroundColorAttributeName
下划线(取值为 NSNumber)
      NSUnderlineStyleAttributeName
下划线颜色(默认:黑色) 
      NSUnderlineColorAttributeName
删除线(取值为 NSNumber)
      NSStrikethroughStyleAttributeName       
/*
    NSUnderlineStyleNone   不设置删除线
    NSUnderlineStyleSingle 设置删除线为细单实线
    NSUnderlineStyleThick  设置删除线为粗单实线
    NSUnderlineStyleDouble 设置删除线为细双实线
*/
删除线颜色(默认:黑色) 
      NSStrikethroughColorAttributeName
是否连体(取值为NSNumber,0 表示字符不连体,1 表示使用默认的连体字符)
      NSLigatureAttributeName
字符间距(取值为 NSNumber,正值加宽)
      NSKernAttributeName
填充部分颜色(取值为 UIColor)
      NSStrokeColorAttributeName
画笔宽度(取值为 NSNumber)
      NSStrokeWidthAttributeName
阴影(取值为 NSShadow)
      NSShadowAttributeName
/*
   NSShadow *shadow1 = [[NSShadow alloc] init];  //NSShadow 对象比较简单,只有3个属性:阴影颜色,模糊半径和偏移
   shadow1.shadowOffset = CGSizeMake(3, 3);      //阴影偏移(X方向偏移和Y方向偏移)
   shadow1.shadowBlurRadius = 0.5;               //模糊半径
   shadow1.shadowColor = [UIColor orangeColor];  //阴影颜色
*/


段落排版(取值为 NSParagraphStyle)
      NSParagraphStyleAttributeName
「
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    paragraphStyle.lineSpacing = self.lineSapce; // 字体的行间距
    paragraphStyle.alignment = NSTextAlignmentJustified; // 文本对齐方式 左右对齐(两边对齐)

属性
     alignment               对齐方式,取值枚举常量 NSTextAlignment
     firstLineHeadIndent     首行缩进,取值 float
     headIndent              除了首行之外的缩进,取值 float
     tailIndent              行尾缩进,取值 float,段落宽
     ineHeightMultiple       可变行高,乘因数,取值 float,改变的是行间距
     maximumLineHeight       最大行高,取值 float,若其值小于默认行高,则行间距变小,若其值大于默认行高,则不会引起任何变化
     minimumLineHeight       最小行高,取值 float,若其值大于默认行高,则行间距变大,若其值小于默认行高,则不会引起任何变化
     lineSpacing             行距,取值 float
     paragraphSpacing        段距,取值 float
     paragraphSpacingBefore  段首空间,取值 float,最小取值为0
     
     baseWritingDirection    句子方向,取值枚举常量 NSWritingDirection
     /*
     NSWritingDirectionLeftToRight  0
     NSWritingDirectionNatural      -1
     NSWritingDirectionRightToLeft  1
     */
     lineBreakMode           断行方式,取值枚举常量 NSLineBreakMode
     /*
      NSLineBreakByWordWrapping = 0, // 自动换行,单词切断
      NSLineBreakByCharWrapping,     // 自动换行,字母切断
      NSLineBreakByClipping,         // 非自动换行,不切断
      NSLineBreakByTruncatingHead,   // 非自动换行,行首切断
      NSLineBreakByTruncatingTail,   // 非自动换行,行尾切断
      NSLineBreakByTruncatingMiddle  // 非自动换行,中间切断
      */
     hyphenationFactor       连字符属性,取值 0 - 1
」

文本附件(取值为NSTextAttachment对象,常用于文字图片混排)
      NSAttachmentAttributeName
链接(取值为NSURL,点击后调用浏览器打开指定URL地址)
      NSLinkAttributeName
文字排版方向(取值为 NSNumber,0 表示横排文本,1 表示竖排文本)
      NSVerticalGlyphFormAttributeName
文字书写方向(从左向右书写或者从右向左书写)
      NSWritingDirectionAttributeName
文本横向拉伸(正值拉伸)
      NSExpansionAttributeName
字体倾斜度(取值为 NSNumber,正值右倾)
      NSObliquenessAttributeName
基线偏移值(取值为 NSNumber,正值上偏)
      NSBaselineOffsetAttributeName
文本特殊效果(取值为 NSString,只印刷有用)
      NSTextEffectAttributeName            

图片文本

    // 文字图片
        NSMutableAttributedString *attribute = [[NSMutableAttributedString alloc] initWithString:[model.name stringByAppendingString:@" "] attributes:@{NSFontAttributeName:kPingFangMediumFont(15)}];
        NSTextAttachment *attchImage = [[NSTextAttachment alloc] init];
        attchImage.image = [UIImage imageNamed:@"home_pinglun_picture.n.png"];
        attchImage.bounds = CGRectMake(0, -3.5 , 18, 18);
        NSAttributedString *stringImage = [NSAttributedString attributedStringWithAttachment:attchImage];
        [attribute appendAttributedString: stringImage];
图片文本(图中的转会)

其他

遍历富文本

    NSMutableAttributedString *muStr=[[NSMutableAttributedString alloc]initWithString:@"" attributes:@{}];
    [muStr enumerateAttribute:NSAttachmentAttributeName inRange:NSMakeRange(0, muStr.length) options:0 usingBlock:^(id  _Nullable value, NSRange range, BOOL * _Nonnull stop) {
        
        if ([value isKindOfClass:[NSTextAttachment class]]) {
            NSTextAttachment * attachment = value;
            CGFloat height = attachment.bounds.size.height;
            attachment.bounds = CGRectMake(0, 0, 300, height);
        }
    }];
超文本转富文本

- (NSAttributedString *)stringFromHtmlStr:(NSString *)htmlStr{
  NSData * htmlData = [htmlStr dataUsingEncoding:NSUTF8StringEncoding];
  NSDictionary * importParams = @{NSDocumentTypeDocumentAttribute:NSHTMLTextDocumentType,NSCharacterEncodingDocumentAttribute:[NSNumber numberWithInt:NSUTF8StringEncoding]};
  NSError * error = nil;
  NSAttributedString * attributeString = [[NSAttributedString alloc] initWithData:htmlData options:importParams documentAttributes:NULL error:&error];
  return attributeString;
}


富文本转超文本

- (NSString *)htmStrFromAttributeStr:(NSAttributedString *)attributeStr{
  NSDictionary * exportParams = @{NSDocumentTypeDocumentAttribute:NSHTMLTextDocumentType,NSCharacterEncodingDocumentAttribute:[NSNumber numberWithInt:NSUTF8StringEncoding]};
  NSData * htmlData = [attributeStr dataFromRange:NSMakeRange:(0, attributeStr.length) documentAttributes:exportParams error:nil];
  htmlString = [[NSString alloc] initwithData:htmlData encoding:NSUTF8StringEncoding];
  return htmlString;
}
修改附件的宽高(防止图片超出)

-(void)method{
    NSMutableAttributedString *muStr=[[NSMutableAttributedString alloc]initWithString:@"" attributes:@{}];
    [muStr enumerateAttribute:NSAttachmentAttributeName inRange:NSMakeRange(0, muStr.length) options:0 usingBlock:^(id  _Nullable value, NSRange range, BOOL * _Nonnull stop) {
        
        if ([value isKindOfClass:[NSTextAttachment class]]) {
            NSTextAttachment * attachment = value;
            CGFloat height = attachment.bounds.size.height;
            attachment.bounds = CGRectMake(0, 0, 300, height);
        }
    }];
}

5. emoji

过滤emoji表情符号

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{
   
    //   限制苹果系统输入法  禁止输入表情
    if ([[[UITextInputMode currentInputMode]primaryLanguage] isEqualToString:@"emoji"]) {
        return NO;
    }

    // 禁止输入emoji表情
    if ([self stringContainsEmoji:text]) {
        return NO;
    }
    
    return YES;
}

// 判断是否输入了emoji 表情
- (BOOL)stringContainsEmoji:(NSString *)string{
    __block BOOL returnValue = NO;
    
    [string enumerateSubstringsInRange:NSMakeRange(0, [string length])
                               options:NSStringEnumerationByComposedCharacterSequences
                            usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) {
                                const unichar hs = [substring characterAtIndex:0];
                                if (0xd800 <= hs && hs <= 0xdbff) {
                                    if (substring.length > 1) {
                                        const unichar ls = [substring characterAtIndex:1];
                                        const int uc = ((hs - 0xd800) * 0x400) + (ls - 0xdc00) + 0x10000;
                                        if (0x1d000 <= uc && uc <= 0x1f77f) {
                                            returnValue = YES;
                                        }
                                    }
                                } else if (substring.length > 1) {
                                    const unichar ls = [substring characterAtIndex:1];
                                    if (ls == 0x20e3) {
                                        returnValue = YES;
                                    }
                                    
                                } else {
                                    if (0x2100 <= hs && hs <= 0x27ff) {
                                        returnValue = YES;
                                    } else if (0x2B05 <= hs && hs <= 0x2b07) {
                                        returnValue = YES;
                                    } else if (0x2934 <= hs && hs <= 0x2935) {
                                        returnValue = YES;
                                    } else if (0x3297 <= hs && hs <= 0x3299) {
                                        returnValue = YES;
                                    } else if (hs == 0xa9 || hs == 0xae || hs == 0x303d || hs == 0x3030 || hs == 0x2b55 || hs == 0x2b1c || hs == 0x2b1b || hs == 0x2b50) {
                                        returnValue = YES;
                                    }else if (hs == 0x200d){
                                        returnValue = YES;
                                    }
                                }
                            }];
    
    return returnValue;
}

6. 第三方键盘IQKeyboardManager

pod 'IQKeyboardManager'
// 开启(默认开启)
    [[IQKeyboardManager sharedManager] setEnable:true];   

// 键盘距正在编辑的TF的距离
    [[IQKeyboardManager sharedManager]setKeyboardDistanceFromTextField:10]; 
// 点击输入框以外收回键盘(默认:false)
    [[IQKeyboardManager sharedManager]setShouldResignOnTouchOutside:true]; 


// 是否显示键盘上方工具条(默认:true)
    [[IQKeyboardManager sharedManager]setEnableAutoToolbar:false]; 
// 键盘上方toolBar是否显示placeHoolder(默认:true)
    [[IQKeyboardManager sharedManager]setShouldShowToolbarPlaceholder:false];
// 键盘上方toolBar文本填充色
    [[IQKeyboardManager sharedManager]setToolbarTintColor:[UIColor blueColor]];
// 键盘上方toolBar的placeHolder字体
    [[IQKeyboardManager sharedManager] setPlaceholderFont:[UIFont systemFontOfSize:18]];

// 管理TF(根据tag)上下箭头   (IQAutoToolbarBySubviews 根据添加顺序   IQAutoToolbarByPosition 根据坐标位置)
    [[IQKeyboardManager sharedManager]setToolbarManageBehaviour:IQAutoToolbarByTag];
// 键盘右上角完成按钮 文本
    [[IQKeyboardManager sharedManager]setToolbarDoneBarButtonItemText:@"右上方按钮文本"];
// 键盘右上角完成按钮 图片
    [[IQKeyboardManager sharedManager] setToolbarDoneBarButtonItemImage:[UIImage imageNamed:@""]];

// 是否可以向下上,向下上
    [[IQKeyboardManager sharedManager]canGoNext];
    [[IQKeyboardManager sharedManager]canGoPrevious];
    [[IQKeyboardManager sharedManager]goNext];
    [[IQKeyboardManager sharedManager]goPrevious];

7. UIFont

系统自带字体

    UIFont *font=[UIFont systemFontOfSize:17];
    UIFont *font2=[UIFont boldSystemFontOfSize:17];
    UIFont *font3=[UIFont italicSystemFontOfSize:17];

    // 获取系统自带字体
    NSArray *fontFamilyArr=[UIFont familyNames];
    for (NSString *familyName in fontFamilyArr) {
        NSArray *fontArray=[UIFont fontNamesForFamilyName:familyName];
        for(NSString *fontName in fontArray){
            NSLog(@"\t%@",fontName); // 输出字体系列下具体字体名 
        }
    }
    // 使用系统自带字体
    #define YTFONT(x,fontName) [UIFont fontWithName:fontName size:(x)]
常用:

  #define kFontLight(a)         ([UIFont fontWithName:@"PingFangSC-Light" size:(a)])
  #define kFontRegular(a)         ([UIFont fontWithName:@"PingFangSC-Regular" size:(a)])
  #define kFontBold(a)           ([UIFont fontWithName:@"PingFangSC-Semibold" size:(a)])
  #define kFontMedium(a)          ([UIFont fontWithName:@"PingFangSC-Medium" size:(a)])
文本处理(UILabel、 UITextField、UITextView、富文本、emoji、IQKeyboardManager、UIFont、UIColor)之iOS笔记摘录_第1张图片
系统字体

自定义字体

1. 导入字体文件 
下载所需ttf文件,复制到项目中
Info.plist中 Fonts provided by application | 字体名.ttf …
项目 |  Build Phases | Copy Bundle Resources 中导入字体

2. 寻找字体名
NSArray *familyNames = [UIFont familyNames];
for( NSString *familyName in familyNames ){
    NSArray *fontNames = [UIFont fontNamesForFamilyName:familyName];
    for( NSString *fontName in fontNames ){
        printf( "\tFont: %s \n", [fontName UTF8String] );
    }
}
打印所有字体名,找到相对应添加的字体名(不能直接使用ttf文件名作为字体名)

3. 使用
#define YTFont_YHS(x) [UIFont fontWithName:@"MicrosoftYaHei-Bold" size:(x)]

8. UIColor

通常控件.alpha是不改的,改背景色.alpha (如果改变label的alpha则它的标题也是透明的)

swift
        
     let c=UIColor.greenColor()                                                 // 创建    
     let c=UIColor.init(red: 120/255.0, green: 120/255.0, blue: 120/255.0, alpha: 1)  // 创建
     let c=UIColor.init(white: 0.5, alpha: 0.5)                       // white:红绿蓝0.5 alpha:0.5
     let c=UIColor.init(patternImage:UIImage(named:”1.png”)).          // 不对图片进行缩放,超出屏幕则裁剪,少则重复添加
     let c=UIColor.clearColor()                                  // 透明色
     let c=UIColor.yellowColor().colorWithAlphaCompoent(0.5)           // 创建(透明度0.0~1.0)

你可能感兴趣的:(文本处理(UILabel、 UITextField、UITextView、富文本、emoji、IQKeyboardManager、UIFont、UIColor)之iOS笔记摘录)