xcode 双空格点击用于文本视图或文本字段iOS

myzjeezk  于 2022-12-27  发布在  iOS
关注(0)|答案(2)|浏览(142)

我正在使用iOS应用程序。在该应用程序中,我有文本字段和文本视图。我的要求是,如果用户点击空格键两次,即使是文本的开始或文本的结束,也要取消键盘。我尝试使用以下代码

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {

    NSLog(@"textView.text %@",textView.text);
    NSUInteger newLength = (textView.text.length - range.length) + text.length;
    //for white space starting
    NSCharacterSet *cs = [[NSCharacterSet characterSetWithCharactersInString:@" "] invertedSet];
    NSString *filtered = [[text componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""];
 
    if([text isEqualToString:@"\n"]) {
        [sendMsgTextView resignFirstResponder];
     //   [self animateTextView:textView up:NO];
        return NO;
       }
    if ([textView.text isEqualToString:filtered]) {
           [sendMsgTextView resignFirstResponder];
        return NO;
    }
 return YES;
}

但问题是它只限制了文本的开始。如果我多次输入文本和点击空格,键盘不会解散或不限制。是否有人对这个问题有想法?如果有,请给予出宝贵的建议。

fjaof16o

fjaof16o1#

请使用下面的解决方案。
在.h文件中
@属性(非原子,保留)NSString *spaceStr;
在.m文件中

**-(BOOL)文本视图:(UITextView *)文本视图应更改范围内的文本:(NSRange)范围替换文本:(NSString *)文本{

if([text isEqualToString:@"\n"]) {
    [self.txtView1 resignFirstResponder];
    //   [self animateTextView:textView up:NO];
    return NO;
}
if ([[self.spaceStr stringByAppendingString:text] isEqualToString:@"  "]) {
    self.spaceStr=@"";
    [self.txtView1 resignFirstResponder];
    return NO;
}
self.spaceStr=text;

return YES;

}

xvw2m8pv

xvw2m8pv2#

我使用了以下代码,使用了以下链接

- (BOOL) textView:(UITextView*)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString*)text
{

 //for restricting the double space for before entering text as well as after entering the text
    if ( (range.location > 0 && [text length] > 0 &&
          [[NSCharacterSet whitespaceCharacterSet] characterIsMember:[text characterAtIndex:0]] &&
          [[NSCharacterSet whitespaceCharacterSet] characterIsMember:[[textView text] characterAtIndex:range.location - 1]]) )

    {
        //Manually replace the space with your own space, programmatically
        textView.text = [textView.text stringByReplacingCharactersInRange:range withString:@""];

        //Make sure you update the text caret to reflect the programmatic change to the text view
        textView.selectedRange = NSMakeRange(range.location+1, 0);

        //Tell Cocoa not to insert its space, because you've just inserted your own
        return NO;
    }
}

并且链路是iPhone: Disable the "double-tap spacebar for ." shortcut?

相关问题