我正在使用下面的代码来尝试让textField2
的文本内容在用户输入textField1
时更新为与textField1
的文本内容相匹配。
- (BOOL) textField: (UITextField *)theTextField shouldChangeCharactersInRange: (NSRange)range replacementString: (NSString *)string {
if (theTextField == textField1){
[textField2 setText:[textField1 text]];
}
}
然而,我观察到的输出是...
textField2为"12",textField1为"123“
当textField1为"1234“时,textField2为"123”
..。当我想要的是:
textField2为"123",textField1为"123“
当textField1为"1234“时,textField2为"1234”
我做错了什么?
发布于 2010-02-04 16:21:04
在文本字段实际更改其文本之前,-shouldChangeCharactersInRange
被调用为,这就是为什么您将获得旧的文本值。要在更新后获取文本,请使用以下命令:
[textField2 setText:[textField1.text stringByReplacingCharactersInRange:range withString:string]];
发布于 2013-04-01 20:58:36
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
NSString * searchStr = [textField.text stringByReplacingCharactersInRange:range withString:string];
NSLog(@"%@",searchStr);
return YES;
}
发布于 2016-11-01 22:59:23
Swift 3
根据接受的答案,以下内容应适用于Swift 3
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
let newString = NSString(string: textField.text!).replacingCharacters(in: range, with: string)
return true
}
备注
String
和NSString
都有名为replacingCharacters:inRange:withString
的方法。但是,不出所料,前者需要一个Range
实例,而后者需要一个NSRange
实例。textField
委托方法使用NSRange
实例,因此在本例中使用NSString
。
https://stackoverflow.com/questions/2198067
复制相似问题