优化UITextField 输入每个字符延时请求,用于联想搜索

UITextField 代理方法-----实时监控输入内容

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    if ([textField.text isEqualToString:@""] && [string isEqualToString:@" "]) {
        return NO;
    }
    NSString *key;
    if ([string isEqualToString:@""]) {
        key = [textField.text substringToIndex:textField.text.length - 1];
    } else {
        key = [NSString stringWithFormat:@"%@%@", textField.text, string];
    }
    
    if ([string isEqualToString:@"\n"]) {
        [self searchDoneButtonAction:nil];
    } else {
        //优化了延迟500毫秒记录输入内容,发起请求
        [NSRunLoop cancelPreviousPerformRequestsWithTarget:self];
        [self performSelector:@selector(afterDelayRequest:) withObject:key afterDelay:0.5];

    }
    return YES;
}

延时请求方法

- (void)afterDelayRequest:(NSString *)key {
    NSLog(@"输入的信息:%@", key);
    if (self.searchInputSearchKeyCompletionHandler) {
                    self.searchInputSearchKeyCompletionHandler(key);
    }
}

你可能感兴趣的:(优化UITextField 输入每个字符延时请求,用于联想搜索)