采用搜索键盘类型,点击键盘的搜索按钮执行搜索,文本内容变化时,执行联想搜索。
输入框设置
- (UITextField *)searchTextField { if(!_searchTextField) { _searchTextField = [self createTextField]; _searchTextField.font = [UIFont systemFontOfSize:13];//字号 _searchTextField.textColor = DEFAULT_TITLE_SUPER_FRONT_COLOR; // NSMutableAttributedString *placeholderString = nil; if(isCommonUnitEmptyString(self.placeholderString)) { _searchTextField.text = @""; } else { // NSMutableAttributedString *placeholderString = [[NSMutableAttributedString alloc] initWithString:@"昵称/个人ID/房间名称" attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:12],NSForegroundColorAttributeName:BGColorHex(CCCCCC)}]; NSMutableAttributedString *placeholderString = [[NSMutableAttributedString alloc] initWithString:self.placeholderString attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:13],NSForegroundColorAttributeName:BGColorHex(888888)}]; _searchTextField.attributedPlaceholder = placeholderString; } _searchTextField.delegate = self; _searchTextField.backgroundColor = [UIColor clearColor]; _searchTextField.keyboardType = UIKeyboardTypeDefault; _searchTextField.returnKeyType = UIReturnKeyGoogle; } return _searchTextField; }
键盘事件处理
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string { if([string isEqualToString:@""]) { if(range.length == string.length) { if (self.deleteBlock) { self.deleteBlock(@""); } } else { NSString *str = [NSString stringWithFormat:@"%@%@", getNotNilString([textField.text substringToIndex:range.location]), getNotNilString([textField.text substringFromIndex:range.location+range.length])]; if (self.deleteBlock) { self.deleteBlock(str); } } return YES; } if(![string isEqualToString:@"\n"] && (textField.text.length + string.length > serarchKeyWordMaxLenght)) { return NO; } if ([string isEqualToString:@"\n"]) { // if (self.deleteBlock) { // self.deleteBlock(textField.text); // } [textField resignFirstResponder]; //检测到用户点击换行或rentun,执行搜索请求 NSString *keyWord = [getNotNilString(textField.text) stringByReplacingOccurrencesOfString:@" " withString:@""]; if(isCommonUnitEmptyString(keyWord)) { return YES; } if(self.searchBlock) { self.searchBlock(keyWord); } [self endEditing:YES]; return NO; } else { NSString *str = [NSString stringWithFormat:@"%@%@%@", getNotNilString([textField.text substringToIndex:range.location]), string, getNotNilString([textField.text substringFromIndex:range.location])]; if (self.deleteBlock) { self.deleteBlock(str); } } return YES; }