因为项目有用到,所以记录下来以后直接用
1.添加代理方法
[self.cardNumberField addTarget:self action:@selector(specialDeal) forControlEvents:UIControlEventEditingChanged];
2.实现方法:
-(void)specialDeal
{
CLog(@"**************");
CLog(@"allCharacter=%d",allCharacter);(记录当前是输入还是删除,用来判断增加空格还是删除空格)
CLog(@"self.cardNumberField=%d",self.cardNumberField.text.length);
CLog(@"**************");
if (allCharacter<self.cardNumberField.text.length) {
if ((self.cardNumberField.text.length)%5==0) {
if (self.cardNumberField.text.length<5) {
}
else{
self.cardNumberField.text=[NSString stringWithFormat:@"%@ %@",[self.cardNumberField.text substringToIndex:self.cardNumberField.text.length-1],[self.cardNumberField.text substringFromIndex:self.cardNumberField.text.length-1]];
CLog(@"%@",self.cardNumberField.text);
}
}
}
else{
if ([self.cardNumberField.text hasSuffix:@" "]) {
self.cardNumberField.text=[self.cardNumberField.text substringToIndex:self.cardNumberField.text.length-1];
}
}
allCharacter=self.cardNumberField.text.length;
}
3.上传
NSString *cardNumber=[self.cardNumberField.text stringByReplacingOccurrencesOfString:@" " withString:@""];
CLog(@"%@",cardNumber);(用以上传给服务器的卡号)