在uipickerview中显示所选值

时间:2014-04-03 09:03:13

标签: ios iphone objective-c cocoa-touch uipickerview

我的详细页面中有一个uipickerview。我想在编辑来自tableviewcell的相应记录时默认选择值。总之,我有一个包含10条记录的tableview。当我从tableview单元格中选择一条记录时,它会导航到详细页面,其中包含三个选择器视图,每个视图包含一个组件。我希望选择器视图默认加载选定的值。以下是Iam如何加载数据的代码。如何在 - (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)行中显示所选值,还有一件事是我正在为此页面使用UINavigationcontroller?伙计们,请你帮帮我

-(void)loadprojects
{
    NSString *post =[[NSString alloc] initWithFormat:@"username=%@",[self.projectpicker dataSource]];
    //NSString *pickername = [self.projectpicker dataSource];
    //NSString *key = @"Da9s^a2Rp4na6R$ikiAsav3Is@niWsa";

    //NSString *encrypteduname = [AESCrypt encrypt:pickername password:key];

    // Code for Project loading
    NSString *projecturltemp = @"http://xxx.xxx/GetAssignedProjects";
    NSString *str = [[NSUserDefaults standardUserDefaults] valueForKey:@"UserLoginIdSession"];
    NSString *usrid = str;
    NSString * projecturl =[NSString stringWithFormat:@"%@/%@",projecturltemp,usrid];


    NSURL *url = [NSURL URLWithString:projecturl];

    NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];




    NSString *postLength = [NSString stringWithFormat:@"%lu", (unsigned long)[postData length]];
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
    [request setURL:url];
    [request setHTTPMethod:@"POST"];
    [request setValue:postLength forHTTPHeaderField:@"Content-Length"];
    [request setValue:@"application/projectpicker" forHTTPHeaderField:@"Accept"];
    [request setValue:@"application/jsonArray" forHTTPHeaderField:@"Content-Type"];
    [request setHTTPBody:postData];


    NSError *error = [[NSError alloc] init];
    NSHTTPURLResponse *response = nil;
    NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
    NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url
                                                cachePolicy:NSURLRequestReturnCacheDataElseLoad
                                            timeoutInterval:30];


    // Make synchronous request
    urlData = [NSURLConnection sendSynchronousRequest:urlRequest
                                    returningResponse:&response
                                                error:&error];
    if ([response statusCode] >= 200 && [response statusCode] < 300)
    {
        NSString *responseData = [NSJSONSerialization JSONObjectWithData:urlData
                                                                 options:NSJSONReadingAllowFragments error:&error];

        NSArray *entries = [NSJSONSerialization JSONObjectWithData:[responseData dataUsingEncoding:NSUTF8StringEncoding]
                                                           options:0 error:&error];
        if(!entries)
        {
            NSLog(@"Error : %@", error);
        }
        else{

            for (NSDictionary *entry in entries) {
                projID = [entries valueForKey:@"ID_PROJECT"];
                projectNames = [entries valueForKey:@"NM_PROJECT"];
            }
            randomSelection=[BenefitNames arrayByAddingObjectsFromArray:projectNames];
            randomSelectionID = [benID arrayByAddingObjectsFromArray:projID];
            _projectpicker.delegate = self;
            _projectpicker.dataSource = self;
        }

    }       else {

    }
}


-(void)loaddata
{
    NSString *eventDate = self.projidstocancel;
    [[NSUserDefaults standardUserDefaults] setObject:eventDate forKey:@"Eventdate"];
    [[NSUserDefaults standardUserDefaults] synchronize];
    NSString *post =[[NSString alloc] initWithFormat:@"username : %@&Password :%@",[self.projectpicker dataSource],[self.projectpicker delegate]];
    //NSString *pickername = [self.projectpicker dataSource];
    //NSString *key = @"Da9s^a2Rp4na6R$ikiAsav3Is@niWsa";

    //NSString *encrypteduname = [AESCrypt encrypt:pickername password:key];

    // Code for Project loading
    NSString *projecturltemp = @"http://xxx.xxxx/GetDetailsByID";
    NSString *str = [[NSUserDefaults standardUserDefaults] valueForKey:@"UserLoginIdSession"];
    NSString *usrid = str;
    NSString * projecturl =[NSString stringWithFormat:@"%@/%@",projecturltemp,self.hdnRowcount];
    NSURL *url = [NSURL URLWithString:projecturl];


    NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];




    NSString *postLength = [NSString stringWithFormat:@"%lu", (unsigned long)[postData length]];
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
    [request setURL:url];
    [request setHTTPMethod:@"POST"];
    [request setValue:postLength forHTTPHeaderField:@"Content-Length"];
    [request setValue:@"application/projectpicker" forHTTPHeaderField:@"Accept"];
    [request setValue:@"application/jsonArray" forHTTPHeaderField:@"Content-Type"];
    [request setHTTPBody:postData];


    NSError *error = [[NSError alloc] init];
    NSHTTPURLResponse *response = nil;
    NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
    NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url
                                                cachePolicy:NSURLRequestReturnCacheDataElseLoad
                                            timeoutInterval:30];


    // Make synchronous request
    urlData = [NSURLConnection sendSynchronousRequest:urlRequest
                                    returningResponse:&response
                                                error:&error];
    if ([response statusCode] >= 200 && [response statusCode] < 300)
    {
        NSString *responseData = [NSJSONSerialization JSONObjectWithData:urlData
                                                                 options:NSJSONReadingAllowFragments error:&error];

        NSArray *entries = [NSJSONSerialization JSONObjectWithData:[responseData dataUsingEncoding:NSUTF8StringEncoding]
                                                           options:0 error:&error];
        if(!entries)
        {
            NSLog(@"Error : %@", error);
        }
        else{

            for (NSDictionary *entry in entries) {
                projectNames = [entries valueForKey:@"NM_PROJECT"];
                taskNames = [entries valueForKey:@"TASk_NAME"];
                subtaskNames = [entries valueForKey:@"SUBTASK_NAME"];
                hdnlblProjects.text = [[entries valueForKey:@"NM_PROJECT"]componentsJoinedByString:@""];
                hdnlblTasks.text = [[entries valueForKey:@"TASk_NAME"]componentsJoinedByString:@""];
                hdnlblSubTasks.text = [[entries valueForKey:@"SUBTASK_NAME"]componentsJoinedByString:@""];
                txthours.text = [[entries valueForKey:@"No_Hours"]componentsJoinedByString:@""];
                txtstatus.text = [[entries valueForKey:@"STATUS"]componentsJoinedByString:@""];
                lblBenefitsLeaves.text = [[entries valueForKey:@"NM_LEAVE"]componentsJoinedByString:@""];
                BenefitNames = [entries valueForKey:@"NM_LEAVE"];
                projID = [entries valueForKey:@"ID_PROJECT"];
                taskID = [entries valueForKey:@"ID_TASK"];
                subtskID = [entries valueForKey:@"ID_SUB_TASK"];
            }
            lblProjects.text = [[projID valueForKey:@"description"] componentsJoinedByString:@""];
            taskstring = [[taskID valueForKey:@"description"] componentsJoinedByString:@""];
            subtaskstring = [[subtskID valueForKey:@"description"] componentsJoinedByString:@""];
            bentest = [[BenefitNames valueForKey:@"description"] componentsJoinedByString:@""];
            hrsdiff1 = [txthours.text floatValue];
        }

    }       else {

    }
}

-(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    return 1;
}
-(NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
    int numberofRows = 0;
    if([pickerView isEqual: _projectpicker]){
        numberofRows = [randomSelection count];
        return numberofRows;
    }
    else if([pickerView isEqual: _taskspicker]){
        numberofRows = [taskNames count];
        return numberofRows;
    }
    else if([pickerView isEqual: _subtaskspicker]){
        numberofRows = [subtaskNames count];
        return numberofRows;
    }
}
-(NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
    NSString *title = @"Test";
    if([pickerView isEqual: _projectpicker]){
        title = [randomSelection objectAtIndex:row];
        return title;
    }

    else if ([pickerView isEqual: _taskspicker]){
        title = [taskNames objectAtIndex:row];
        return title;
    }
    else if ([pickerView isEqual: _subtaskspicker]){
        title = [subtaskNames objectAtIndex:row];
        return title;
    }

}

-(void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
    //NSLog(@"%@",myArrayString);
    //NSLog(@"%@",myTaskArrayString);
   if([pickerView isEqual: _projectpicker]){
        NSNumber *myProjectArrayString = [randomSelectionID objectAtIndex:row];
        lblProjects.text = [NSString stringWithFormat:@"%@",myProjectArrayString];
        lblProjects.hidden = YES;
        lblBenefitsLeaves.text = [randomSelection objectAtIndex:row];
        hdnlblProjects.text = [randomSelection objectAtIndex:row];
        rownoedit = row;
       lblTasks.text = @"0";
       hdnlblTasks.text = @"--Select--";
       lblSubTasks.text = @"0";
       hdnlblSubTasks.text = @"--Select--";
        [self loadtasks];

    }
    //lblProjects.hidden = YES;
    else if([pickerView isEqual: _taskspicker])
    {
        NSNumber *myTaskArrayString = [taskID objectAtIndex:row];
        lblTasks.text = [NSString stringWithFormat:@"%@",myTaskArrayString];
        lblTasks.hidden = YES;
        hdnlblTasks.text = [taskNames objectAtIndex:row];
        lblSubTasks.text = @"0";
        hdnlblSubTasks.text = @"--Select--";
        [self loadsubtasks];

    }
    else if([pickerView isEqual: _subtaskspicker])
    {
        NSNumber *mysubtaskArrayString = [subtskID objectAtIndex:row];
        lblSubTasks.text = [NSString stringWithFormat:@"%@",mysubtaskArrayString];
        lblSubTasks.hidden = YES;
        hdnlblSubTasks.text = [subtaskNames objectAtIndex:row];

        //lblTasks.text = [taskNames objectAtIndex:[pickerView selectedRowInComponent:1]];
        //lblTasks.text = [NSString stringWithFormat:@"%@", myTaskArrayString];
        //lblSubTasks.text = [subtaskNames objectAtIndex:[pickerView selectedRowInComponent:2]];
    }
}

3 个答案:

答案 0 :(得分:1)

首先定义一个静态变量,并在加载时首先给它初始值

ex:static int selectedRow = 3

-(void)pickerView:(UIPickerView *)pickerView didSelectRow:
(NSInteger)row inComponent:(NSInteger)component{
selectedRow = [pickerView selectedRowInComponent:0];

}

然后你在哪里显示pickerView放置这一行

  [self selectRow:selectedRow inComponent:0 animated:YES];

答案 1 :(得分:0)

尝试使用以下代码

[self.yourPickerViewName selectRow:self.valueName inComponent:0 animated:YES];

哪里

self.valueName是从tableview单元格中选择记录的值。并在创建UIPickerView.

后输入上面的代码

答案 2 :(得分:0)

您可以将其引用以从pickerview

中获取所选值
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
    if([pickerView isEqual:StatePicker])
    {
      stateName = [StateArray objectAtIndex:row]; //StateName is NSString, StateArray is Array
    }
}