ios 细节一下实时搜索
2018-08-03 本文已影响93人
雪_晟
前言
在实时搜索的时候,我们需要根据输入框搜索内容配合后台实时搜索。对于自定义的搜索框,我们使用的方法如下:
[self.textField addTarget:self action:@selector(textValueChanged) forControlEvents:UIControlEventEditingChanged];
- (void)textValueChanged
{
NSLog(@"%@",self.textField.text);
}
效果图如下:

可以做到实时搜索,但是如果输入的中文,未确定最终输入之前也会一直调用接口,导致调用太频繁,后台压力太大。如果能在确定了输入内容之后再进行搜索就么么哒了。
优化
UITextInput
的一个属性介绍:
/* If text can be selected, it can be marked. Marked text represents provisionally
* inserted text that has yet to be confirmed by the user. It requires unique visual
* treatment in its display. If there is any marked text, the selection, whether a
* caret or an extended range, always resides witihin.
*
* Setting marked text either replaces the existing marked text or, if none is present,
* inserts it from the current selection. */
@property (nullable, nonatomic, readonly) UITextRange *markedTextRange; // Nil if no marked text.
经过测试可以发现,如果输入是的中文,输入框中有未确定的高亮选中时,markedTextRange
是非空,当确定了输入内容之后,为nil。
//获取是否有高亮 UITextRange *selectedRange = [self.searchTF markedTextRange];
selectedRange为空。所以我们再加一层判断即可。
if (self.searchTF.text.length >0) {
//获取是否有高亮
UITextRange *selectedRange = [self.searchTF markedTextRange];
if (!selectedRange) {
NSLog(@"调用接口");
}
最后的效果

End