我希望在我的应用中自动填充UITextFiled。在用户键入一些字母时,它将调用Web服务并在UIpPickerView中显示响应,以便搜索城市。当我们输入任何字母时,它会显示一些城市名称。谁能知道该怎么做?请帮我。
答案 0 :(得分:3)
要以异步方式从服务器获取数据,您可以使用NSURLConnection
和NSURLConnectionDelegate
方法
在界面文件中:
@interface ViewController : UIViewController<NSURLConnectionDelegate, UITextFieldDelegate> {
NSMutableData *mutableData;
}
-(void)getDataUsingText:(NSString *)text;
@end
在实施档案中:
@implementation ViewController
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
NSString *value =[textField.text stringByReplacingCharactersInRange:range withString:string];
[self getDataUsingText:value];
return YES;
}
-(void)getDataUsingText:(NSString *)text;
{
NSString *urlString = [NSString stringWithFormat:@"http://...."];
NSURL *url =[NSURL URLWithString:urlString];
NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url];
NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[conn start];
}
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
mutableData = [[NSMutableData alloc] init];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[mutableData appendData:data];
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSString *dataString = [[NSString alloc] initWithData:mutableData encoding:NSUTF8StringEncoding];
NSLog(@"your data from server: %@", dataString);
// Here you got the data from server asynchronously.
// Here you can parse the string and reload the picker view using [picker reloadAllComponents];
}
@end
您必须将委托设置为文本字段,并且必须使用NSURLConnectionDelegate
方法中的数据实现选择器。 this是一个加载选择器视图的教程。