在 UITextView 上将给定字符串替换为另一个字符串
在我的应用程序上,我需要这样做:当在 TextView 上键入字符时,将其保存在 NSString 上,然后用“*”替换。我尝试了这个:
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
NSLog(@"typing...");
text=@"*";
passwordText=textView.text;
NSLog(@"password %@",passwordText);
NSString* nextText = [textView.text stringByReplacingCharactersInRange:range withString:text];
textView.text=nextText;
NSLog(@"next %@",nextText);
NSLog(@"textview.text %@",textView.text);
return YES;
}
其中 passwordText
是 NSString
,我想在其中保存从键盘引入的文本 UITextView
。
结果是这样的: http://i54.tinypic.com/2cx9ueo.png (这里我引入了“我们”,我看到了这个:“*w*e”。
我提到我必须使用 UITextView 而不是 UITextField 来解决这个问题。
On my app I need to do this: when a character is typed on TextView to be saved on a NSString and after that to be replace with '*'. I tried this :
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
NSLog(@"typing...");
text=@"*";
passwordText=textView.text;
NSLog(@"password %@",passwordText);
NSString* nextText = [textView.text stringByReplacingCharactersInRange:range withString:text];
textView.text=nextText;
NSLog(@"next %@",nextText);
NSLog(@"textview.text %@",textView.text);
return YES;
}
where passwordText
is the NSString
in which I want to save the text introduce from keyboard on UITextView
.
The result is this : http://i54.tinypic.com/2cx9ueo.png (here I introduced 'we' and I see this :'*w*e'. Can anyone help me to solve this?
I mention that I must do this using UITextView
, and not UITextField.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我可以告诉你为什么你会得到带有 * 的字符,尽管我不确定你的方法是否值得经历这个。
将返回语句设置为“否”,这将丢弃按下的新键。 YES 当前将该字符放置在程序性“*”旁边。
I can tell you why you get character along with the *, though i am not sure whether your approach is worth to go through this.
make your return statement as NO, this will discard the new key pressed. The YES is currently placing that character next to your programmatic '*'.
如果您希望立即进行更改,只需在方法中返回 NO 即可。如果您希望它有点延迟(即首先显示一个字符,然后像密码字段中那样用 * 替换),请返回 YES 并运行 textView
:shouldChangeTextInRange:replacementText: 方法中的另一个方法,该方法将在 0.5 秒后触发(或另一个方法)如果你愿意的话)使用计时器。
这个新方法可以用*替换最后添加的字符或更改的字符。
Just return a NO in the method if you want the change to be immediate. If you want it to be a little delayed (i.e. first show a character then replace with * like in password fields), return a YES and run another method from the
textView:shouldChangeTextInRange:replacementText: method to be fired after 0.5 seconds (or another number if you like) using a timer.
This new method can replace the last added character or changed character with a *.