IOS-如何幹掉UITextField的長按手勢菜單與輸入內容限制 – iPhone手機開發技術文章 iPhone軟體開發教學課程

今天項目用到瞭這個就寫一下,方便以後同學不會的時候可以直接使用

首先要重寫UITextFiled子類 在初始化方法下面 copy 下面方法 就禁止瞭長按出現的菜單

//幹掉textField
的長按菜單 禁止copy paste

-(BOOL)canPerformAction:(SEL)action withSender:(id)sender

{

if ([UIMenuController
sharedMenuController]) {

[UIMenuController
sharedMenuController].menuVisible =
NO;

}

return
NO;

}

在開發中我們有時候會對UITextFiled 進行一些操作,說一下如何隻輸入中文,或者 隻輸入 數字 和英文 2中方法

我直接用宏定義定義:

#define kAlphaNum @”abcdefghijklmnopqrstuvwxyz” //這種是對應隻輸入中文 不允許其他數字或者符號的

#define kEnglishNum @”ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789″ //這種是對應隻能輸入數字和英文的方法

執行UITextField 的delegate 方法 切記 textFiled.delegate = self;

下面直接上代碼:

– (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range
replacementString:(NSString *)string

{

UITextField *nameField = (UITextField *)[self
viewWithTag:200];

UITextField *cardField = (UITextField *)[self
viewWithTag:201];

if (textField == nameField) {

//隻允許輸入中文

NSCharacterSet *cs;

cs = [[NSCharacterSet
characterSetWithCharactersInString:kAlphaNum]
invertedSet];

NSString *filtered = [[string
componentsSeparatedByCharactersInSet:cs]
componentsJoinedByString:@””];

BOOL basic = [string
isEqualToString:filtered];

NSString *text = [textField.text
stringByReplacingCharactersInRange:range
withString:string];

if (_delegate && [_delegate
respondsToSelector:@selector(passName:)]) {

[_delegate
passName:text];

}

return basic;

}

if (textField == cardField) {

//隻允許輸入英文和數字

NSCharacterSet *cs;

cs = [[NSCharacterSet
characterSetWithCharactersInString:kEnglishNum]
invertedSet];

NSString *filtered = [[string
componentsSeparatedByCharactersInSet:cs]
componentsJoinedByString:@””];

BOOL basic = [string
isEqualToString:filtered];

NSString *text = [textField.text
stringByReplacingCharactersInRange:range
withString:string];

if (_delegate && [_delegate
respondsToSelector:@selector(passCard:)]) {

[_delegate
passCard:text];

}

return basic;

}

return
YES;

}

發佈留言