我想删除返回键输入的换行符。但是,当我执行以下操作时,它会删除文本中的最后一个字符。为什么呢?
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text;
{
NSLog(@"%d %d %@ %@",range.location,range.length, text, [textView text]);
if ( [text isEqualToString:@"\n"] ) {
NSString *s = [textView text];
s = [s substringToIndex:[s length] - 1]; // <------------
[tvText setText:[NSString stringWithFormat:@"%@\n>>",s]];
}
return YES;
}
我希望结果如下:
>>name
>>yoda
>> <---- cursor is moved to the right of ">>"
答案 0 :(得分:4)
我认为你可以做这样的事情,
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text;
{
NSLog(@"%d %d %@ %@",range.location,range.length, text, [textView text]);
if ( [text isEqualToString:@"\n"] ) {
[tvText setText:[NSString stringWithFormat:@"%@\n>>",tvText.text]];
return NO;
}
return YES;
}
答案 1 :(得分:4)
或者也许在你读完字符串之后把它放到一些子字符串中:
string = [string stringByReplacingOccurrencesOfString:@"\n;" withString:@""];
答案 2 :(得分:3)
shouldChangeTextInRange是UITextViewDelegate的一部分,在之前被称为,在textView中更改了新文本。因此,您可以这样做:
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text;
{
if ([text isEqualToString:@"\n"])
{
return NO;
}
return YES;
}
答案 3 :(得分:2)
使用此功能可获得更好的解决方案,因为它不会允许用户在任何情况下发布任何空白消息。
//These for loops will remove the spaces and new line characters from start and end of the string
//&&//
NSMutableString *temp = [[NSMutableString alloc] initWithString:posttextview.text];
//Remove spaces and new line characters from start
for(int i = 0; i < yourtext.length; i++)
{
NSString *temp1 = [NSMutableString stringWithString:[temp substringWithRange:NSMakeRange(0,1)]];
if([temp1 isEqualToString:@"\n"] || [temp1 isEqualToString:@" "])
{
[temp deleteCharactersInRange:NSMakeRange(0,1)];
}
else
{
break;
}
}
yourtext.text = temp;
//Remove spaces and new line characters from end
for(int i = 0; i < yourtext.length; i++)
{
NSString *temp1 = [NSMutableString stringWithString:[temp substringWithRange:NSMakeRange(posttextview.text.length - 1,1)]];
if([temp1 isEqualToString:@"\n"] || [temp1 isEqualToString:@" "])
{
[temp deleteCharactersInRange:NSMakeRange(posttextview.text.length - 1,1)];
yourtext.text = temp;
}
else
{
break;
}
}
yourtext.text = temp;
//**//
答案 4 :(得分:1)
问题是时间shouldChangeCharactersImRange被调用,新文本实际上还没有改变(这就是为什么它没有命名为didChangeCharactersInRange ...)。因此,如果您遇到换行符,请不要使用子字符串进行操作,只需存储/处理文本视图到目前为止包含的字符串,然后返回NO。
答案 5 :(得分:0)
首先在.h文件中添加UITextViewDelegate
@interface YourClass : UITextField <UITextFieldDelegate> {
}
然后实现委托方法
-(BOOL)shouldChangeCharactersInRange:replacementString: