iOS基礎(chǔ)之文本處理(UILabel、 UITextField、UITextView、富文本、emoji、IQKeyboardManager、UIFont、UIColor)

目錄

    1. UILabel: UIView  文本展示
    2. UITextField: UIControl    文本編輯框(單行)
    3. UITextView: UIScrollView     文本編輯框(多行)

    4. NSMutableAttributedString  復(fù)雜文本(富文本)
    5. emoji 
    6. 第三方鍵盤IQKeyboardManager
    7. UIFont
    8. UIColor

1. UILabel 文本控件( : UIView)

// 創(chuàng)建label
UILabel *textLabel=[UILabel new];
[self.view addSubview:textLabel];
[textLabel autoPinEdgesToSuperviewEdgesWithInsets:UIEdgeInsetsZero];

常用

文本、字體、顏色、對(duì)齊方式、行數(shù)、省略模式

    // 設(shè)置 文本 
    [textLabel setText:@""];
    // 設(shè)置 復(fù)雜文本
    [textLabel setAttributedText:[NSAttributedString new]];
    // 設(shè)置 字體
    [textLabel setFont:[UIFont systemFontOfSize:16]];
    // 設(shè)置 顏色
    [textLabel setTextColor:[UIColor colorWithWhite:0.35 alpha:1]];
    // 設(shè)置 對(duì)齊方式(左 右 居中)
    [textLabel setTextAlignment:NSTextAlignmentLeft];
    /
       NSTextAlignmentLeft (iOS9之前為默認(rèn))
       NSTextAlignmentRight
       NSTextAlignmentCenter
      NSTextAlignmentJustified
      NSTextAlignmentNatural(iOS9之后為默認(rèn))
    /
    // 設(shè)置 行數(shù)(默認(rèn):1 ,0:則無限行)
    [textLabel setNumberOfLines:0];
    // 設(shè)置 省略mode(文本超范圍時(shí))
    [textLabel setLineBreakMode:NSLineBreakByClipping];
    /
       ByWordWrapping         以單詞為顯示單位顯示(后面部分不顯示)(默認(rèn))
       ByCharWrapping         以字符為顯示單位顯示(后面部分不顯示)
       ByClipping             剪切與控件寬度相同的內(nèi)容長(zhǎng)度(后半部分被刪除)
       ByTruncatingHead       前面以…省略,尾部正常顯示
       ByTruncatingTail       尾部以…省略,頭部正常顯示(常用)
       ByTruncatingMiddle     中間以…省略,頭尾正常顯示
     /
縮放

  // 是否根據(jù)文本內(nèi)容和控件大小來改變字體大?。J(rèn):false)
  [textLabel setAdjustsFontSizeToFitWidth:true];
  // 最小縮放系數(shù)
  [textLabel setMinimumScaleFactor:6.0];
可交互

    // UILabel 和 UIImageView等少數(shù)控件,其userInteractionEnabled屬性默認(rèn)為false(即不可交互)
    // 設(shè)置 是否允許交互
    [textLabel setUserInteractionEnabled:true];

    // 設(shè)置 是否禁用控件 , 
    [textLabel setEnabled:true];
去除str兩端的空格
  [str stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];

對(duì)URL百分號(hào)編碼(標(biāo)點(diǎn)符號(hào)/中文->百分號(hào))
  [str stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
移除百分號(hào)編碼
  [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

文本自適應(yīng)

// 獲取高度/寬度

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           // 鍵盤已經(jīng)顯示
    UIKeyboardWillHideNotification          // 鍵盤即將隱藏
    UIKeyboardDidHideNotification           // 鍵盤已經(jīng)隱藏
    /*
    UIKeyboardFrameBeginUserInfoKey         // NSValue of CGRect
    UIKeyboardFrameEndUserInfoKey           // NSValue of CGRect  鍵盤顯示后
    UIKeyboardAnimationDurationUserInfoKey  // NSNumber of double 動(dòng)畫時(shí)長(zhǎng)
    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];

常用

    // 設(shè)置 文本、富文本
    [contentTF setText:@""];
    [contentTF setAttributedText:[[NSAttributedString alloc]initWithString:@"" attributes:@{
    }]];
    // 設(shè)置 字體
    [contentTF setFont:[UIFont systemFontOfSize:17]];
    // 設(shè)置 顏色
    [contentTF setTextColor:[UIColor redColor]];
    // 設(shè)置 對(duì)齊方式
    [contentTF setTextAlignment:NSTextAlignmentLeft];
    /*
     NSTextAlignmentLeft
     NSTextAlignmentCenter
     NSTextAlignmentRight
     */
    // 設(shè)置 提示富文本
    [contentTF setAttributedPlaceholder:[[NSMutableAttributedString alloc]initWithString:@"placeholder" attributes:@{
    }]];
/*
    // 設(shè)置 提示文本
    [contentTF setPlaceholder:@""];
    // 前提:必須先設(shè)置placeholder
    // 設(shè)置 提示文本顏色
    [contentTF setValue:[UIColor darkGrayColor] forKeyPath:@"_placeholderLabel.textColor"];
    // 設(shè)置 提示文本字體
    [contentTF setValue:[UIFont systemFontOfSize:14] forKeyPath:@"_placeholderLabel.font"];
*/
    // 設(shè)置 是否加密顯示
    [contentTF setSecureTextEntry:true];
    // 獲得焦點(diǎn)(成為第一響應(yīng)者)
    [contentTF becomeFirstResponder];
    // 失去焦點(diǎn)(注銷第一響應(yīng)者)
    //(只能隱藏自己的鍵盤,不能隱藏其他textF的鍵盤)
    [contentTF resignFirstResponder];
    // 結(jié)束所有編輯狀態(tài)(隱藏所有鍵盤)
    [self.view endEditing:true];

    // 內(nèi)容改變后回調(diào)
    [contentTF addTarget:self action:@selector(textfieldContentChange:) forControlEvents:UIControlEventEditingChanged];
    //-------------- 右側(cè)x視圖 --------------
    // 設(shè)置 右側(cè)x視圖Mode
    [contentTF setClearButtonMode:UITextFieldViewModeAlways];
    /*
     UITextFieldViewModeNever,              從不顯示
     UITextFieldViewModeWhileEditing,       僅編輯時(shí)
     UITextFieldViewModeUnlessEditing,      除了編輯
     UITextFieldViewModeAlways              一直顯示
     */
    // 設(shè)置 是否插入文本時(shí)清空數(shù)據(jù)
    [contentTF setClearsOnInsertion:true];
    //-------------- 兩側(cè)視圖 --------------
    // 設(shè)置 左側(cè)視圖mode
    [contentTF setLeftViewMode:UITextFieldViewModeAlways];
    /*
     UITextFieldViewModeNever,              從不顯示
     UITextFieldViewModeWhileEditing,       僅編輯時(shí)
     UITextFieldViewModeUnlessEditing,      除了編輯
     UITextFieldViewModeAlways              一直顯示
     */
    // 設(shè)置 左側(cè)視圖
    [contentTF setLeftView:[UIView new]];
    // 設(shè)置 右側(cè)視圖mode、右側(cè)視圖
    // 右視圖會(huì)覆蓋x清空按鈕
    [contentTF setRightViewMode:UITextFieldViewModeAlways];
    [contentTF setRightView:[UIView new]];
    //-------------- 鍵盤 --------------
    // 設(shè)置 鍵盤Mode
    [contentTF setKeyboardType:UIKeyboardTypeNumberPad];
    /*
     UIKeyboardTypeDefault                  默認(rèn)的 鍵盤
     UIKeyboardTypeASCIICapable             純英文字母的 鍵盤
     UIKeyboardTypeNumbersAndPunctuation    數(shù)字和標(biāo)點(diǎn)的 鍵盤
     UIKeyboardTypeURL                      便于輸入數(shù)字的 鍵盤 (.com)
     UIKeyboardTypeNumberPad                便于輸入數(shù)字的 鍵盤(純數(shù)字)
     UIKeyboardTypePhonePad                 便于撥號(hào)呼叫的 鍵盤(手機(jī)號(hào))
     UIKeyboardTypeNamePhonePad             便于聊天撥號(hào)的 鍵盤
     UIKeyboardTypeEmailAddress             便于輸入Email的 鍵盤 (@)
     UIKeyboardTypeDecimalPad               用于輸入數(shù)字和【小數(shù)點(diǎn)】的 鍵盤
     UIKeyboardTypeTwitter                  便于在網(wǎng)頁(yè)上書寫的 鍵盤
     UIKeyboardTypeWebSearch
     UIKeyboardTypeASCIICapableNumberPad
     UIKeyboardTypeAlphabet
     */
    // 設(shè)置 鍵盤外觀
    [contentTF setKeyboardAppearance:UIKeyboardAppearanceDark];
    /*
     UIKeyboardAppearanceDefault,   淺灰色(默認(rèn)顏色)
     UIKeyboardAppearanceDark       黑色
     UIKeyboardAppearanceLight      亮色,與Default很相似
     UIKeyboardAppearanceAlert
     */
    // 設(shè)置鍵盤右下角return按鈕標(biāo)題
    [contentTF setReturnKeyType:UIReturnKeyDone];
    /*
     UIReturnKeyDefault,    完成
     UIReturnKeyGo,         完成并跳到另一頁(yè)
     UIReturnKeyGoogle,     搜索
     UIReturnKeyJoin,       注冊(cè)用戶或添加數(shù)據(jù)
     UIReturnKeyNext,       繼續(xù)下一步
     UIReturnKeyRoute,      發(fā)送
     UIReturnKeySearch,
     UIReturnKeySend,
     UIReturnKeyYahoo,
     UIReturnKeyDone,
     UIReturnKeyEmergencyCall,
     UIReturnKeyContinue
     */

    // 設(shè)置 自定義鍵盤View
    [contentTF setInputView:[UIView new]];
    // 設(shè)置 自定義鍵盤上方View
    [contentTF setInputAccessoryView:[UIView new]];
    //-------------- 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];
    //-------------- 其他 --------------
    // 設(shè)置邊框Mode
    [contentTF setBorderStyle:UITextBorderStyleNone];
    /*
     UITextBorderStyleNone,         無邊框
     UITextBorderStyleLine,         直線
     UITextBorderStyleBezel,        邊線+陰影
     UITextBorderStyleRoundedRect   圓角    (默認(rèn)白色背景,此時(shí)背景圖無效)
     */
    // 設(shè)置 背景色、背景圖片
    [contentTF setBackgroundColor:[UIColor blueColor]];
    [contentTF setBackground:[UIImage imageNamed:@""]]; // 邊框樣式需為none
    [contentTF setDisabledBackground:[UIImage imageNamed:@""]];
    // 設(shè)置 內(nèi)容縱向?qū)R方式
    [contentTF setContentVerticalAlignment:UIControlContentVerticalAlignmentTop];
    /*
     UIControlContentVerticalAlignmentCenter
     UIControlContentVerticalAlignmentTop
     UIControlContentVerticalAlignmentBottom
     UIControlContentVerticalAlignmentFill
     */
    // 設(shè)置 內(nèi)容橫向?qū)R方式
    [contentTF setContentHorizontalAlignment:UIControlContentHorizontalAlignmentLeft];
    /*
     UIControlContentHorizontalAlignmentCenter
     UIControlContentHorizontalAlignmentLeft
     UIControlContentHorizontalAlignmentRight
     UIControlContentHorizontalAlignmentFill
     UIControlContentHorizontalAlignmentLeading
     UIControlContentHorizontalAlignmentTrailing
     */
    // 設(shè)置 是否自動(dòng)補(bǔ)全
    [contentTF setAutocorrectionType:UITextAutocorrectionTypeNo];
    /*
     UITextAutocorrectionTypeDefault,
     UITextAutocorrectionTypeNo,        不自動(dòng)更正
     UITextAutocorrectionTypeYes,       自動(dòng)更正
     */
    // 設(shè)置 文本隨控件縮放
    [contentTF setAdjustsFontSizeToFitWidth:true];
    // 設(shè)置 最小縮放字體
    [contentTF setMinimumFontSize:14];

dele

    // <UITextFieldDelegate>
    [contentTF setDelegate:self];

// 是否允許開始編輯
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField{return true;}
// 開始編輯后調(diào)用
- (void)textFieldDidBeginEditing:(UITextField *)textField{}
// 是否允許結(jié)束編輯
- (BOOL)textFieldShouldEndEditing:(UITextField *)textField{return true;}
// 結(jié)束編輯后調(diào)用
- (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發(fā)出的通知:
    UITextFieldTextDidBeginEditingNotification  
    UITextFieldTextDidEndEditingNotification        
    UITextFieldTextDidChangeNotification            // 用于聯(lián)想詞匯
// 由鍵盤視圖發(fā)出的通知:
    UIKeyboardWillShowNotification 即將彈出時(shí) 發(fā)送
    UIKeyboardDidShowNotification  完成彈出時(shí) 發(fā)送
    UIKeyboardWillHideNotification 即將隱藏時(shí) 發(fā)送
    UIKeyboardDidHideNotification  完成隱藏時(shí) 發(fā)送
    UIKeyboardWillChangeFrameNotification 即將改變frame時(shí) 發(fā)送
    UIKeyboardDidChangeFrameNotification  完成改變frame時(shí) 發(fā)送

IQKeyboardManager第三方(方便鍵盤管理)

    pod 'IQKeyboardManager'

3. UITextView 多行文本(: UIScrollView)

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

    // 設(shè)置 文本
    [contentTV setText:@""];
    // 設(shè)置 富文本
    [contentTV setAttributedText:[NSAttributedString new]];
    // 設(shè)置 字體
    [contentTV setFont:[UIFont systemFontOfSize:15]];
    // 設(shè)置 顏色
    [contentTV setTextColor:[UIColor redColor]];
    // 設(shè)置 對(duì)齊方式
    [contentTV setTextAlignment:NSTextAlignmentLeft];

    // 設(shè)置 文本是否可選
    [contentTV setSelectable:true];
    // 設(shè)置 允許選擇的范圍
    [contentTV setSelectedRange:NSMakeRange(0, 10)];

    // 設(shè)置 文本是否可編輯
    [contentTV setEditable:true];
    // 設(shè)置 是否允許滾動(dòng)
    [contentTV setScrollEnabled:true];
    // 滾動(dòng)至指定范圍
    [contentTV scrollRangeToVisible:NSMakeRange(0, 10)];

    // 成為第一響應(yīng)者
    [contentTV becomeFirstResponder];
    // 注銷第一響應(yīng)者
    [contentTV resignFirstResponder];

    // 自定義 鍵盤View
    [contentTV setInputView:[UIView new]];
    // 自定義 鍵盤上方View
    [contentTV setInputAccessoryView:[UIView new]];
    // 設(shè)置 frame(基本不用)
    [contentTV setFrame:CGRectZero];
    // 設(shè)置 背景色
    [contentTV setBackgroundColor:[UIColor blueColor]];
    // 設(shè)置 邊框色、邊寬寬度
    [contentTV.layer setBorderColor:[UIColor blueColor].CGColor];
    [contentTV.layer setBorderWidth:1.0];
    // 設(shè)置 圓角
    [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];


// 開始編輯前調(diào)用(是否允許開始編輯)
- (BOOL)textViewShouldBeginEditing:(UITextView *)textView{return true;}
// 開始編輯后調(diào)用
- (void)textViewDidBeginEditing:(UITextView *)textView{}
// 結(jié)束編輯前調(diào)用(是否允許結(jié)束編輯)
- (BOOL)textViewShouldEndEditing:(UITextView *)textView{return true;}
// 結(jié)束編輯后調(diào)用
- (void)textViewDidEndEditing:(UITextView *)textView{}
// 編輯內(nèi)容后調(diào)用(是否允許改變)用于控制字符長(zhǎng)度
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{ return true;}
// 文本內(nèi)容改變后調(diào)用
- (void)textViewDidChange:(UITextView *)textView{}
// 選中文本變化后調(diào)用
- (void)textViewDidChangeSelection:(UITextView *)textView{}

4. NSMutableAttributedString 復(fù)雜文本(富文本)

    // 創(chuàng)建(文本Font,文本Color)
    NSMutableAttributedString *muStr=[[NSMutableAttributedString alloc]initWithString:@"" attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:11],NSForegroundColorAttributeName:[UIColor blueColor]}];
    // 追加單個(gè)屬性(背景色)
    [muStr addAttribute:NSBackgroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(0, 10)];
    // 追加多個(gè)屬性(下劃線)
    [muStr addAttributes:@{NSUnderlineStyleAttributeName:@(2),NSUnderlineColorAttributeName:[UIColor blueColor]} range:NSMakeRange(0, 10)];
    // 字符間距(正數(shù)則 加寬),基線偏移(正數(shù)則 上偏),字符是否連體(0沒有連體字符,1默認(rèn)的連體字符)
    [muStr setAttributes:@{NSKernAttributeName:@(10),NSBaselineOffsetAttributeName:@(10),NSLigatureAttributeName:@(2)} range:NSMakeRange(0, 10)];


文本字體(默認(rèn)值:字體:Helvetica(Neue) ,字號(hào):12)
      NSFontAttributeName
文本顏色(默認(rèn)值:黑色)
      NSForegroundColorAttributeName
背景色(默認(rèn)值為nil, 透明色)
      NSBackgroundColorAttributeName
下劃線(取值為 NSNumber)
      NSUnderlineStyleAttributeName
下劃線顏色(默認(rèn):黑色) 
      NSUnderlineColorAttributeName
刪除線(取值為 NSNumber)
      NSStrikethroughStyleAttributeName       
/*
    NSUnderlineStyleNone   不設(shè)置刪除線
    NSUnderlineStyleSingle 設(shè)置刪除線為細(xì)單實(shí)線
    NSUnderlineStyleThick  設(shè)置刪除線為粗單實(shí)線
    NSUnderlineStyleDouble 設(shè)置刪除線為細(xì)雙實(shí)線
*/
刪除線顏色(默認(rèn):黑色) 
      NSStrikethroughColorAttributeName
是否連體(取值為NSNumber,0 表示字符不連體,1 表示使用默認(rèn)的連體字符)
      NSLigatureAttributeName
字符間距(取值為 NSNumber,正值加寬)
      NSKernAttributeName
填充部分顏色(取值為 UIColor)
      NSStrokeColorAttributeName
畫筆寬度(取值為 NSNumber)
      NSStrokeWidthAttributeName
陰影(取值為 NSShadow)
      NSShadowAttributeName
/*
   NSShadow *shadow1 = [[NSShadow alloc] init];  //NSShadow 對(duì)象比較簡(jiǎn)單,只有3個(gè)屬性:陰影顏色,模糊半徑和偏移
   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; // 文本對(duì)齊方式 左右對(duì)齊(兩邊對(duì)齊)

屬性
     alignment               對(duì)齊方式,取值枚舉常量 NSTextAlignment
     firstLineHeadIndent     首行縮進(jìn),取值 float
     headIndent              除了首行之外的縮進(jìn),取值 float
     tailIndent              行尾縮進(jìn),取值 float,段落寬
     ineHeightMultiple       可變行高,乘因數(shù),取值 float,改變的是行間距
     maximumLineHeight       最大行高,取值 float,若其值小于默認(rèn)行高,則行間距變小,若其值大于默認(rèn)行高,則不會(huì)引起任何變化
     minimumLineHeight       最小行高,取值 float,若其值大于默認(rèn)行高,則行間距變大,若其值小于默認(rèn)行高,則不會(huì)引起任何變化
     lineSpacing             行距,取值 float
     paragraphSpacing        段距,取值 float
     paragraphSpacingBefore  段首空間,取值 float,最小取值為0
     
     baseWritingDirection    句子方向,取值枚舉常量 NSWritingDirection
     /*
     NSWritingDirectionLeftToRight  0
     NSWritingDirectionNatural      -1
     NSWritingDirectionRightToLeft  1
     */
     lineBreakMode           斷行方式,取值枚舉常量 NSLineBreakMode
     /*
      NSLineBreakByWordWrapping = 0, // 自動(dòng)換行,單詞切斷
      NSLineBreakByCharWrapping,     // 自動(dòng)換行,字母切斷
      NSLineBreakByClipping,         // 非自動(dòng)換行,不切斷
      NSLineBreakByTruncatingHead,   // 非自動(dòng)換行,行首切斷
      NSLineBreakByTruncatingTail,   // 非自動(dòng)換行,行尾切斷
      NSLineBreakByTruncatingMiddle  // 非自動(dòng)換行,中間切斷
      */
     hyphenationFactor       連字符屬性,取值 0 - 1
」

文本附件(取值為NSTextAttachment對(duì)象,常用于文字圖片混排)
      NSAttachmentAttributeName
鏈接(取值為NSURL,點(diǎn)擊后調(diào)用瀏覽器打開指定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];
圖片文本(圖中的轉(zhuǎn)會(huì))

其他

遍歷富文本

    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);
        }
    }];
超文本轉(zhuǎn)富文本

- (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;
}


富文本轉(zhuǎn)超文本

- (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表情符號(hào)

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{
   
    //   限制蘋果系統(tǒng)輸入法  禁止輸入表情
    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'
// 開啟(默認(rèn)開啟)
    [[IQKeyboardManager sharedManager] setEnable:true];   

// 點(diǎn)擊輸入框以外收回鍵盤(默認(rèn):false)
    [[IQKeyboardManager sharedManager]setShouldResignOnTouchOutside:true]; 
// 鍵盤距正在編輯的TF的距離
    [[IQKeyboardManager sharedManager]setKeyboardDistanceFromTextField:10]; 

// 是否顯示鍵盤上方工具條(默認(rèn):true)
    [[IQKeyboardManager sharedManager]setEnableAutoToolbar:false]; 
// 鍵盤上方toolBar是否顯示placeHoolder(默認(rèn):true)
    [[IQKeyboardManager sharedManager]setShouldShowToolbarPlaceholder:false];
// 鍵盤上方toolBar文本填充色
    [[IQKeyboardManager sharedManager]setToolbarTintColor:[UIColor blueColor]];
// 鍵盤上方toolBar的placeHolder字體
    [[IQKeyboardManager sharedManager] setPlaceholderFont:[UIFont systemFontOfSize:18]];

// 管理TF(根據(jù)tag)上下箭頭   (IQAutoToolbarBySubviews 根據(jù)添加順序   IQAutoToolbarByPosition 根據(jù)坐標(biāo)位置)
    [[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

系統(tǒng)自帶字體

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

    // 獲取系統(tǒng)自帶字體
    NSArray *fontFamilyArr=[UIFont familyNames];
    for (NSString *familyName in fontFamilyArr) {
        NSArray *fontArray=[UIFont fontNamesForFamilyName:familyName];
        for(NSString *fontName in fontArray){
            NSLog(@"\t%@",fontName); // 輸出字體系列下具體字體名 
        }
    }
    // 使用系統(tǒng)自帶字體
    #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)])
系統(tǒng)字體

自定義字體

1. 導(dǎo)入字體文件 
下載所需ttf文件,復(fù)制到項(xiàng)目中
Info.plist中 Fonts provided by application | 字體名.ttf …
項(xiàng)目 |  Build Phases | Copy Bundle Resources 中導(dǎo)入字體

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] );
    }
}
打印所有字體名,找到相對(duì)應(yīng)添加的字體名(不能直接使用ttf文件名作為字體名)

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

8. UIColor

通常控件.alpha是不改的,改背景色.alpha (如果改變label的alpha則它的標(biāo)題也是透明的)

swift
        
     let c=UIColor.greenColor()                                                 // 創(chuàng)建    
     let c=UIColor.init(red: 120/255.0, green: 120/255.0, blue: 120/255.0, alpha: 1)  // 創(chuàng)建
     let c=UIColor.init(white: 0.5, alpha: 0.5)                       // white:紅綠藍(lán)0.5 alpha:0.5
     let c=UIColor.init(patternImage:UIImage(named:”1.png”)).          // 不對(duì)圖片進(jìn)行縮放,超出屏幕則裁剪,少則重復(fù)添加
     let c=UIColor.clearColor()                                  // 透明色
     let c=UIColor.yellowColor().colorWithAlphaCompoent(0.5)           // 創(chuàng)建(透明度0.0~1.0)
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 227,572評(píng)論 6 531
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 98,071評(píng)論 3 414
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事?!?“怎么了?”我有些...
    開封第一講書人閱讀 175,409評(píng)論 0 373
  • 文/不壞的土叔 我叫張陵,是天一觀的道長(zhǎng)。 經(jīng)常有香客問我,道長(zhǎng),這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 62,569評(píng)論 1 307
  • 正文 為了忘掉前任,我火速辦了婚禮,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 71,360評(píng)論 6 404
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 54,895評(píng)論 1 321
  • 那天,我揣著相機(jī)與錄音,去河邊找鬼。 笑死,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 42,979評(píng)論 3 440
  • 文/蒼蘭香墨 我猛地睜開眼,長(zhǎng)吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 42,123評(píng)論 0 286
  • 序言:老撾萬榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個(gè)月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 48,643評(píng)論 1 333
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 40,559評(píng)論 3 354
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 42,742評(píng)論 1 369
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,250評(píng)論 5 356
  • 正文 年R本政府宣布,位于F島的核電站,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 43,981評(píng)論 3 346
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 34,363評(píng)論 0 25
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 35,622評(píng)論 1 280
  • 我被黑心中介騙來泰國(guó)打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 51,354評(píng)論 3 390
  • 正文 我出身青樓,卻偏偏與公主長(zhǎng)得像,于是被迫代替她去往敵國(guó)和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 47,707評(píng)論 2 370

推薦閱讀更多精彩內(nèi)容

  • 1、通過CocoaPods安裝項(xiàng)目名稱項(xiàng)目信息 AFNetworking網(wǎng)絡(luò)請(qǐng)求組件 FMDB本地?cái)?shù)據(jù)庫(kù)組件 SD...
    陽明先生_X自主閱讀 16,000評(píng)論 3 119
  • 去年從開通公眾號(hào)到年末,總共發(fā)了 7 篇文章,涵蓋了 5 個(gè)主題:創(chuàng)業(yè),工作,游戲,讀書,產(chǎn)品,很發(fā)散,很隨意。通...
    閉眼賣布閱讀 237評(píng)論 0 0
  • 北風(fēng)微涼,南風(fēng)未起。 故國(guó)深秋景,異域纏綿情。 西風(fēng)吹,東風(fēng)殘。 楓葉凋零臘月寒。 片片葉,處處景, 守得伊人醉,...
    十六維閱讀 224評(píng)論 2 3
  • 我的童年是屬于外婆家的,因?yàn)槲医?jīng)常被送去,一去就是幾個(gè)月,有時(shí)實(shí)在想家,才被送回來,而我記憶中,每次回家,家門口的...
    月下荷影閱讀 216評(píng)論 0 0