iOS 之UITextFiled/UITextView小結

一:編輯被鍵盤遮擋的問題    (推薦使用第三方庫:IQKeyboardManager  用法參考

 參考自:http://blog.csdn.net/windkisshao/article/details/21398521html

1.自定方法 ,用於移動視圖

-(void)moveInputBarWithKeyboardHeight:(float)_CGRectHeight withDuration:(NSTimeInterval)_NSTimeInterval;數組

2.註冊監聽

NSNotificationCenter *defaultCenter = [NSNotificationCenter defaultCenter];服務器

    [defaultCenter selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];app

    [defaultCenter addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];ssh

3.實現方法

- (void)keyboardWillShow:(NSNotification *)notification {iphone

    NSDictionary *userInfo = [notification userInfo];ide

    NSValue* aValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];字體

    CGRect keyboardRect = [aValue CGRectValue];atom

    NSValue *animationDurationValue = [userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey];spa

    NSTimeInterval animationDuration;

    [animationDurationValue getValue:&animationDuration];

    if(nil==self.myTextView) return;//    self.editTextView 爲被鍵盤遮擋住的控件

    CGRect rect = self.myTextView.frame;

    float textY = rect.origin.y + rect.size.height; 

    float bottomY = SCREENHEIGHT - textY;//獲得下邊框到底部的距離  SCREENHEIGHT 爲當前設備的高度

    if(bottomY >=keyboardRect.size.height ){//鍵盤默認高度,若是大於此高度,則直接返回

        return;

    }

    float moveY = keyboardRect.size.height - bottomY;

    [self moveInputBarWithKeyboardHeight:moveY withDuration:animationDuration];

}

 

- (void)keyboardWillHide:(NSNotification *)notification {

    NSDictionary* userInfo = [notification userInfo];

    NSValue *animationDurationValue = [userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey];

    NSTimeInterval animationDuration;

    [animationDurationValue getValue:&animationDuration];

    [self moveInputBarWithKeyboardHeight:0.0 withDuration:animationDuration];

}

 

-(void)moveInputBarWithKeyboardHeight:(float)_CGRectHeight withDuration:(NSTimeInterval)_NSTimeInterval{

  CGRect rect1 = self.view.frame;

    [UIView beginAnimations:nil context:NULL];

    [UIView setAnimationDuration:_NSTimeInterval];

    rect1.origin.y = -_CGRectHeight;//view往上移動

    self.view.frame = rect1;

    [UIView commitAnimations];

}

二: 鍵盤

(1)鍵盤類型 

     UIKeyboardTypeDefault, // 默認鍵盤:支持全部字符 

  1.  UIKeyboardTypeASCIICapable, // 支持ASCII的默認鍵盤 
  2.  UIKeyboardTypeNumbersAndPunctuation, // 標準電話鍵盤,支持+*#等符號 
  3.  UIKeyboardTypeURL, // URL鍵盤,有.com按鈕;只支持URL字符 
  4.  UIKeyboardTypeNumberPad,  //純數字鍵盤 (不帶小數點)
  5.  UIKeyboardTypeDecimalPad  //數字鍵盤 (帶小數點)
  6.  UIKeyboardTypePhonePad,   // 電話鍵盤 
  7.  UIKeyboardTypeNamePhonePad, // 電話鍵盤,也支持輸入人名字 
  8.  UIKeyboardTypeEmailAddress, // 用於輸入電子郵件地址的鍵盤
  9.  UIKeyboardTypeWebSearch     //用於搜索
  10. UIKeyboardTypeAlphabet

   如:  self.uIphone.keyboardType = UIKeyboardTypeNumberPad;

   祥見:http://blog.csdn.net/crazyzhang1990/article/details/39965931

(2) return鍵的類型 

       UIReturnKeyDefault, 默認 灰色按鈕,標有Return 

     UIReturnKeyGo,     標有Go的藍色按鈕           (完成,可用於填寫資料的最後一項)

     UIReturnKeyGoogle,標有Google的藍色按鈕,用語搜索 

     UIReturnKeyJoin,標有Join的藍色按鈕 

     UIReturnKeyNext,標有Next的藍色按鈕             (可用於登陸/註冊/填寫地址-->下一步)

     UIReturnKeyRoute,標有Route的藍色按鈕 

     UIReturnKeySearch,標有Search的藍色按鈕     (可用於搜索)

     UIReturnKeySend,標有Send的藍色按鈕          

     UIReturnKeyYahoo,標有Yahoo的藍色按鈕 

     UIReturnKeyYahoo,標有Yahoo的藍色按鈕 

     UIReturnKeyEmergencyCall, 緊急呼叫按鈕

  如:

 self.uIphone.keyboardType = UIKeyboardTypeNumberPad;

(3) 點擊return建響應事件

   A.UITextField --> - (BOOL)textFieldShouldReturn:(UITextField *)textField{

   如:  添加地址

- (BOOL)textFieldShouldReturn:(UITextField *)textField{

    if(textField.tag==10)  //下一步 (姓名)

    {

        [self.uName resignFirstResponder];

        [self.uIphone becomeFirstResponder];

    }else if(textField.tag==11)   //下一步 (電話)

    {

        [self.uIphone resignFirstResponder];

        [self.reciveAddress becomeFirstResponder];

    }else if(textField.tag==100)   //完成(地址填完以後可直接調用接口)

    {

        [self.reciveAddress resignFirstResponder];

         [self addBtn:nil];     

    }

    return YES;

}

B.UITextView --> - (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text

如:

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{
    if ([text isEqualToString:@"\n"]){ //判斷輸入的字是不是回車,即按下return
        //在這裏作你響應return鍵的代碼

         [self addBtn:nil];

        return NO; //這裏返回NO,就表明return鍵值失效,即頁面上按下return,不會出現換行,若是爲yes,則輸入頁面會換行
    }

    return YES;
}

參考自:http://blog.sina.com.cn/s/blog_59fb90df010176re.html

 

三:UITextField小結

   1.自定義UITextField 左邊加圖標(如:登陸)

    UIImageView *i=[[UIImageView alloc]initWithFrame:CGRectMake(15, 10, 21, 21)];

    [i setImage:[UIImage imageNamed:@"yh"]];

    UIView *userLeftView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 40, 38)];

    [userLeftView addSubview:i]; 

    self.userName.leftView=userLeftView;

    self.userName.leftViewMode=UITextFieldViewModeAlways;

     若只是單純的UITextField 縮進: 只需加  self.userName.leftViewMode=UITextFieldViewModeAlways; self.userName.leftView=[[UIView alloc]init] 兩句便可。

   2.設置自定義UITextField 的Placeholder顏色   

   (1)方法一:

       UIColor *color = [UIColor blue];

    self.userName.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"  手機號"  attributes:@{NSForegroundColorAttributeName: color}];

(2)方法二:        

   [textField setValue:[UIColor redColor] forKeyPath:@"_placeholderLabel.textColor"]; 

   [textField setValue:[UIFont boldSystemFontOfSize:16] forKeyPath:@"_placeholderLabel.font"];

   3.統一收起鍵盤      

    [[[UIApplication sharedApplication] keyWindow] endEditing:YES];

    4. textFiled  自動換行           

          http://blog.csdn.net/u012661893/article/details/52183456

四:UITextView小結

  1.設置Placeholder      

    @property (nonatomic,strong) UILabel  *proText1;        

    self.automaticallyAdjustsScrollViewInsets = NO;    

    [self.leaveMessage setDelegate:self];

    UILabel *lbl=[[UILabel alloc]initWithFrame:CGRectMake(self.leaveMessage.frame.origin.x+10, self.leaveMessage.frame.origin.y-35, self.leaveMessage.bounds.size.width, 100)];

    lbl.text=@" 感謝您留下寶貴的意見....";

    [lbl setFont:[UIFont systemFontOfSize:15.0]];

    lbl.enabled=NO;

    self.proText1=lbl;

    [self.view addSubview:lbl];    

  #pragma mark -----textView的代理事件

  -(void)textViewDidChange:(UITextView *)textView

  {

   //  textView.text = [textView.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];

        if (textView.text.length == 0) {

            self.proText1.text = @" 感謝您留下寶貴的意見....";

        }else{

            self.proText1.text = @"";

        }

  }

2.去掉空格以及換行

 NSString *content = [textView.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];

有的時候因爲不正確的操做,直接將textView.text做爲參數傳 到服務器,可能會產生意想不到的錯誤,所以就須要加這個對字符串進行一下處理

 

3. 限制輸入長度

    實現代理方法:

- (void)textViewDidChange:(UITextView *)textView{

     NSString *toBeString = [textView.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];

    //獲取高亮部分

    UITextRange *selectedRange = [textView markedTextRange];

    UITextPosition *position = [textView positionFromPosition:selectedRange.start offset:0];

    

    // 沒有高亮選擇的字,則對已輸入的文字進行字數統計和限制

    if (!position)

    {

        if (toBeString.length > MAX_STARWORDS_LENGTH)

        {

            [MBProgressHUD showAlert:@"最多隻能輸入150個字。"];

            NSRange rangeIndex = [toBeString rangeOfComposedCharacterSequenceAtIndex:MAX_STARWORDS_LENGTH];

            if (rangeIndex.length == 1)

            {

                textView.text = [toBeString substringToIndex:MAX_STARWORDS_LENGTH];

            }

            else

            {

                NSRange rangeRange = [toBeString rangeOfComposedCharacterSequencesForRange:NSMakeRange(0, MAX_STARWORDS_LENGTH)];

                textView.text = [toBeString substringWithRange:rangeRange];

            }

        }

    }

}

 

 

 更多請參考:http://www.41443.com/HTML/iphone/20141109/204260.html

 

補充:   

1.長按複製功能

 - (void)viewDidLoad { 

     [self.view addGestureRecognizer:[[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(pasteBoard:)]]; 

}

 - (void)pasteBoard:(UILongPressGestureRecognizer *)longPress { 

          if (longPress.state == UIGestureRecognizerStateBegan) {

                             UIPasteboard *pasteboard = [UIPasteboard generalPasteboard]; 

                              pasteboard.string = @"須要複製的文本";

          } }

 

2.導入自定義字體庫

     一、找到你想用的字體的 ttf 格式,拖入工程

     二、在工程的plist中增長一行數組,「Fonts provided by application」

     三、爲這個key添加一個item,value爲你剛纔導入的ttf文件名

     四、直接使用便可:label.font = [UIFont fontWithName:@"你剛纔導入的ttf文件名" size:20.0];

 附:計算文字的size

/**
 *  計算一段文字size
 */
- (CGSize)sizeWithFont:(UIFont *)font maxW:(CGFloat)maxW
{
    NSMutableDictionary *attrs = [NSMutableDictionary dictionary];
    attrs[NSFontAttributeName] = font;
    CGSize maxSize = CGSizeMake(maxW, MAXFLOAT);
    
    return [self boundingRectWithSize:maxSize options:NSStringDrawingUsesLineFragmentOrigin attributes:attrs context:nil].size;
    
}
/**
 *  計算一行文字size
 */
- (CGSize)sizeWithFont:(UIFont *)font
{
    return [self sizeWithFont:font maxW:MAXFLOAT];
}
相關文章
相關標籤/搜索