2

我想在我的应用程序中自动填充 UITextFiled。当用户在其中输入一些字母时,它将调用 Web 服务并在 UIpPickerView 中显示响应,例如搜索城市。当我们输入任何字母时,它会显示一些城市名称。谁能知道该怎么做?请帮我。

4

1 回答 1

3

要从服务器异步获取数据,您可以使用NSURLConnectionandNSURLConnectionDelegate方法

在接口文件中:

@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方法中的数据实现选择器。这是加载选择器视图的教程

于 2012-08-13T13:37:29.723 回答