1 #import "AppDelegate.h" 2 3 @interface AppDelegate ()<UITextFieldDelegate>// 添加代理协议 4 5 @end 6 7 @implementation AppDelegate 8 9 10 - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { 11 self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]]; 12 // Override point for customization after application launch. 13 self.window.backgroundColor = [UIColor whiteColor]; 14 15 16 UITextField *tf = [[UITextField alloc] initWithFrame:CGRectMake(60, 100, 180, 30)]; 17 //确认代理 18 tf.delegate = self; 19 tf.keyboardType = UIKeyboardAppearanceDefault; 20 21 tf.backgroundColor = [UIColor greenColor]; 22 [self.window addSubview:tf]; 23 24 [self.window makeKeyAndVisible]; 25 return YES; 26 } 27 28 - (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string 29 { 30 int length = [textField.text length]; 31 // 2代表*号的起始位置,9代表*号的结束位置 32 if (length > 2 && length < 9) { 33 NSMutableString *text = [textField.text mutableCopy]; 34 [text replaceCharactersInRange:NSMakeRange(length - 1 , 1) withString:@"*"]; 35 textField.text = text; 36 } 37 return YES; 38 } 39 40 @end
实现的效果如下图:
时间: 2024-11-05 12:27:56