首先我們來說一說字數(shù)限制的問題
由于TextField的代理方法
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string; // return NO to not change text
當(dāng)輸入框內(nèi)容有變化時,其不能完全捕捉到變化祟峦,所以我們做字數(shù)限制時,最好不要用此方法。我們可以通過給textfield添加事件的方法來限制其字數(shù)壁肋,
[textfield addTarget:self action:@selector(textFieldValueChange:) forControlEvents:UIControlEventValueChanged];
其中textFieldValueChange是當(dāng)textfield內(nèi)容有變化時就會調(diào)用凌埂,下面我們開始在此方法中限制字數(shù)
-(void) textFieldValueChange:(UITextField *) textfield
{
//因為輸入內(nèi)容可能是漢字,所以要在沒有高亮的時候腕够,來獲取當(dāng)前輸入框的內(nèi)容逊脯,再去限制字數(shù)优质,否則會有crash
UITextRange *textRange = [textView markedTextRange];
UITextPosition *position = [textView positionFromPosition:textRange.start offset:0];
if (!position)
{
NSString *textStr = textView.text;
if (textStr.length>500)
{
textfield.text = [textStr substringToIndex:500];
}
}
}
下面來討論鍵盤遮蓋問題
這是我們常見到的狀況,所以不做解釋了军洼,直接說解決方法巩螃。
首先我們添加一個鍵盤的NSNotification
[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyboardDidChangeFrame:) name:UIKeyboardWillChangeFrameNotification object:nil];
然后在接收通知的地方獲取鍵盤的y值變化,根據(jù)此y值來改變你需要改變的view
//解決鍵盤遮蓋問題
-(void)keyboardDidChangeFrame:(NSNotification *)noti
{
NSDictionary *userInfo = noti.userInfo;
// 動畫的持續(xù)時間
double duration = [userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
// 鍵盤的frame
CGRect keyboardF = [userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
//鍵盤的Y值
CGFloat keyboardY = keyboardF.origin.y;
//根據(jù)鍵盤的Y值來改變你需要改變的View
}