Установить текст UILabel из Plist? - PullRequest
3 голосов
/ 20 марта 2011

Я успешно загрузил свои списки и словари в свои таблицы.Я пытаюсь установить для значенияличного упражнения значение «UILabel» в подробном представлении моего упражнения.

<array>
<dict>
    <key>exercises</key>
    <array>
        <dict>
            <key>exerciseDetail</key>
            <string></string>
            <key>exerciseName</key>
            <string>Ab Crunch Machine</string>
        </dict>
        <dict>
            <key>exerciseDetail</key>
            <string></string>
            <key>exerciseName</key>
            <string>Ab Roller</string>
        </dict>
    </array>
    <key>muscleName</key>
    <string>Abdominals</string>
</dict>

В данный момент подробное описание упражнения пустое, но в конечном итоге загрузит UILabel или UITextView в подробном представлении того же упражнения.

Я предполагаю, что мне нужно сделать что-то вроде

label.text =[[self.exerciseArray objectAtIndex:indexPath.row]objectForKey:@"exercises"];

РЕДАКТИРОВАТЬ:

Для моего упражненияViewController didSelectIndexAtRow у меня есть:

NSUserDefaults *def = [NSUserDefaults standardUserDefaults];
    [def setObject:exerciseArray forKey:@"exercises"];
    [def setValue:[NSString stringWithFormat:@"%d",indexPath.row] forKey:@"exercises"];

и для ViewDidLoad дляdetailViewController У меня есть: viewDidLoad для exercDetailView

 self.navigationItem.title = @"Exercise Detail"; 

NSMutableArray *exerciseDetailArray = [[[NSUserDefaults alloc] objectForKey:@"exercises"] mutableCopy];

int indexValue = [[[NSUserDefaults alloc] valueForKey:@"exercises"] intValue];

name.text =[[exerciseDetailArray objectAtIndex:indexValue] objectForKey:@"exerciseName"];

Консольный вывод:

2011-03-19 22:52:08.279 Curl[32300:207] exercisedetalarray: (
    {
    exerciseDetail = "";
    exerciseName = "Ab Crunch Machine";
},
    {
    exerciseDetail = "";
    exerciseName = "Ab Roller";
},
    {
    exerciseDetail = "";
    exerciseName = "Advanced Kettlebell Windmill";
},
    {
    exerciseName = "Air Bike";
},
    {
    exerciseName = "Alternate Heel Touchers";
},
    {
    exerciseName = "Barbell Ab Rollout";
},
    {
    exerciseName = "Barbell Side Bend";
},
    {
    exerciseName = "Bent Press";
},
    {
    exerciseName = "Bent-Knee Hip Raise";
},
    {
    exerciseName = "Butt-Ups";
},
    {
    exerciseName = "Cable Crunch";
}

)

2011-03-19 22:52:08.280 Curl[32300:207] index value: 0

Редактировать с помощью MaserView NSDefault code:

NSUserDefaults *def = [NSUserDefaults standardUserDefaults];
[def setObject:exerciseArray forKey:@"InfoArray"];
[def setValue:[NSString stringWithFormat:@"%d",indexPath.row] forKey:@"indexVal"];

Редактировать с подробным видом. Код NSUserDefaults:

-(void)viewWillAppear:(BOOL)animated
{    
    NSMutableArray *exerciseDetailArray = [[[NSUserDefaults alloc] objectForKey:@"InfoArray"] mutableCopy];

    int indexValue = [[[NSUserDefaults alloc] valueForKey:@"indexVal"] intValue];

    name.text =[[exerciseDetailArray objectAtIndex:indexValue] objectForKey:@"exerciseName"];
}

1 Ответ

9 голосов
/ 20 марта 2011

@ Фейсал:

Глядя на ваш код, я предполагаю, что ваши метки находятся под вашим tableView, так как вы используете indexPath.row для индексации массива

Ваша идея выглядит правильно.

ШАГ-1:

Извлечение данных из plist в ваш массив ( Plist -> Array )

Скажем, если ваше plist-имя Exercise.plist, то вы можете использовать следующий код для извлечения ваших данных в plist

NSString* plistPath = [[NSBundle mainBundle] pathForResource:@"Exercise" ofType:@"plist"];
exerciseArray = [NSArray arrayWithContentsOfFile:plistPath];

ШАГ-2:

Получить данные из массива в текст метки ( Массив -> Текст метки )

Затем установите текст UILabel из значений массива, используя приведенный ниже код

label.text =[[exerciseArray objectAtIndex:indexPath.row]objectForKey:@"exercises"];

ПРИМЕЧАНИЕ:

Для использования одного и того же массива между вами masterView и detailView вы можете установить свой массив в NSUserDefaults на didSelectRowAtIndexPath в вашем masterView и получить тот же массив в detailView.

Вы можете сделать это, используя следующий код:

В masterView для didSelectRowAtIndexPath метод:

NSUserDefaults *def = [NSUserDefaults standardUserDefaults];
[def setObject:exerciseArray forKey:@"InfoArray"];
[def setValue:[NSString stringWithFormat:@"%d",indexPath.row] forKey:@"indexVal"];

Вы можете получить этот массив в detailView, используя следующий код:

NSMutableArray *exerciseDetailArray = [[[NSUserDefaults standardUserDefaults] objectForKey:@"InfoArray"] mutableCopy];

int indexValue = [[[NSUserDefaults standardUserDefaults] valueForKey:@"indexVal"] intValue];

label.text =[[exerciseDetailArray objectAtIndex:indexValue] objectForKey:@"exercises"]; 

OR

NSArray *exerciseDetailArray = [[NSArray alloc] initWithContentsOfArray:[[NSUserDefaults alloc] objectForKey:@"InfoArray"]];

int indexValue = [[[NSUserDefaults standardUserDefaults] valueForKey:@"indexVal"] intValue];

label.text =[[exerciseDetailArray objectAtIndex:indexValue] objectForKey:@"exercises"]; 

Надеюсь, это поможет вам:)

Окончательное редактирование:

Замените ваш метод didSelectRowAtIndexPath: на метод, описанный ниже в SpecificExerciseTableViewController.m

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Navigation logic may go here. Create and push another view controller.

     DetailViewController *detailViewController = [[DetailViewController alloc] initWithNibName:@"DetailViewController" bundle:nil];
     detailViewController.exerciseArray = [[self.exerciseArray objectAtIndex:indexPath.row]objectForKey:@"exercises"];
     // Pass the selected object to the new view controller.


    NSUserDefaults *def = [NSUserDefaults standardUserDefaults];
    [def setObject:exerciseArray forKey:@"InfoArray"];
    [def setValue:[NSString stringWithFormat:@"%d",indexPath.row] forKey:@"indexVal"];
    NSLog(@"Index inexpath:%d",indexPath.row);
    int indexValue = [[[NSUserDefaults standardUserDefaults] valueForKey:@"indexVal"] intValue];
    NSLog(@"index value master view: %d",indexValue);

    [self.navigationController pushViewController:detailViewController animated:YES];
    [detailViewController release];

}

Это наверняка сработает:)

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...