,如果有人想它迅速... 創建名爲txtSearch一個文本框,然後在viewDidLoad中添加下面兩行
self.txtSearch.delegate=self
self.txtSearch.addTarget(self, action: #selector(self.textFieldValueChanged(TextField:)), for: UIControlEvents.editingChanged)
func textFieldValueChanged(TextField:UITextField)
{
if((TextField.text?.characters.count)!>0)
{
self.filteredArray = (self.searchInArray(srchArray: self.ArraywithFullData, withKey: "key value", Characters: TextField.text!))!
}
else
{
self.filteredArray = self.ArraywithFullData.mutableCopy() as! NSMutableArray
}
self.pickerView.reloadData()
}
func searchInArray(srchArray:NSMutableArray, withKey:String,Characters:String)->NSMutableArray
{
let resultArray=NSMutableArray()
for index in 0..<srchArray.count
{
let Dict = srchArray[index] as! [String:Any]
if let stringmatcher = Dict[withKey] as? String
{
if(stringmatcher.contains(find: Characters))
{
resultArray.add(Dict)
}
else
{
}
}
}
return resultArray
}
extension String {
func contains(find: String) -> Bool{
return self.range(of: find) != nil
}
和Objective-C的你必須做一些像下面。但不要忘記調用textField Delegates。
NSMutableArray *filteredArray;
NSMutableArray *ArraywithFullData;
self.txtSearch.delegate=self
[self.txtSearch addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
//
-(void)textFieldValueChanged:(UITextField *)TextField
{
if((TextField.text.length)>0)
{
filteredArray = [self searchInArray:ArraywithFullData withKey:@"key value" andCharacters:TextField.text];
}
else
{
filteredArray = [ArraywithFullData mutableCopy];
}
[self.pickerView reloadData];
}
-(NSMutableArray *)searchInArray:(NSMutableArray*)srchArray withKey:(NSString *)key andCharacters:(NSString *)charecters
{
NSMutableArray *resultArray= [[NSMutableArray alloc]init];
for (int index=0 ; index<srchArray.count; index++)
{
NSMutableDictionary *Dict = srchArray[index];
if ([Dict valueForKey:key] != nil)
{
NSString * stringmatcher = [Dict valueForKey:key];
if ([stringmatcher containsString:charecters])
{
[resultArray addObject:Dict];
}
else
{
}
}
}
return resultArray;
}
如果數據不是字典,你可以刪除代碼的工作,是關於字典
哈桑先生的陣列的形式注,我的代碼是在Objective C,所以我不能夠理解上面的SWIFT代碼,你可以發佈它的目標C代碼(如果可以的話),否則我會試着去理解這段代碼。 –
好吧讓我把它轉換成目標 - C –
更新了代碼請檢查它。現在它有兩個。語言....可能不是完全正確的,但你必須這樣做。 –