Как я могу нажать TableView при нажатии кнопки и инициализировать TableViewCell с NSDictionary? - PullRequest
0 голосов
/ 17 января 2012

Может кто-нибудь, пожалуйста, помогите мне о том, как подтолкнуть представление таблицы при нажатии кнопки. Я хочу загрузить сообщения из NSMutableArray в ячейки табличного представления, а NSMutableArray загружается с данными, проанализированными из URL-адреса.

-(IBAction)readMessages:(id)sender
{
    // i want to push the tableview when clicking the button in relation with this method
    // WHAT MUST I DO HERE?

   }

Вместо того, чтобы задавать новый вопрос, мне понравилось редактировать этот, так как дело в том же аспекте. Теперь я могу создать табличное представление программно, но я не могу инициализировать его ячейки данными, полученными из массива Json. Вот мой код:

NSString *str1=[@"?username=" stringByAppendingString:userNameField.text];
        NSString *str2=[@"&password=" stringByAppendingString:passwordField.text];
        NSString *str3=[str1 stringByAppendingString:str2];
        NSString *str4 =[@"http://" stringByAppendingString:serverField.text];


        NSURL *url=[NSURL URLWithString:[str4 stringByAppendingString:[@"/ipad/login.php" stringByAppendingString:str3]]];
        //get the url to jsondata
        NSData *jSonData=[NSData dataWithContentsOfURL:url];

        if (jSonData!=nil) {
            NSError *error=nil;
            id result=[NSJSONSerialization JSONObjectWithData:jSonData options:
                       NSJSONReadingMutableContainers error:&error];
            if (error==nil) {
                NSDictionary *mess=[result objectForKey:@"message"];
                NSDictionary *messContent=[mess valueForKeyPath:@"message"];
                NSDictionary *messID=[mess valueForKeyPath:@"ID"];
                NSString*key1=[ result objectForKey:@"key" ];                
                NSString *s1=[@"http://" stringByAppendingString:serverField.text];
                NSString *s2=[s1 stringByAppendingString:@"/ipad/button.php"];
                NSURL *url2=[NSURL URLWithString:[s2 stringByAppendingString:[@"?key=" stringByAppendingString:key1]]];

                NSData *data2=[NSData dataWithContentsOfURL:url2];
                id result2=[NSJSONSerialization JSONObjectWithData:data2 options:NSJSONReadingMutableContainers error:nil];

                 mesID = [NSMutableArray array];//saving meesage ID s to NSMutableArray
                 content = [NSMutableArray array];    
               // i logged here and it saves  the data, now i want to display my data in table view

                for (NSDictionary *data in mess) {
                    [mesID addObject:[data objectForKey:@"ID"]];
                    [content addObject:[data objectForKey:@"message"]];        
                    [[NSUserDefaults standardUserDefaults] setObject:messID forKey:@"message"];
                    [[NSUserDefaults standardUserDefaults] setObject:messContent forKey:@"messContent"];

                    //messID will be saved as the Title of the cells and messContent will be displayed as the text area of that cell, opening in a new view

И это вывод, я хочу установить заголовки ячеек в качестве идентификатора и их содержание в виде текста:

  2012-01-17 16:26:59.873 ipad_Teslim[940:f803] MessID: (
        1,
        3
    )
    2012-01-17 16:26:59.875 ipad_Teslim[940:f803] Content: (
        asdf,
        "this is a test"
    )

Как я уже упоминал в своем коде, messID будет сохранен как заголовок ячеек, а messContent будет отображаться как текстовая область этой ячейки, открывающаяся в новом представлении. Как я могу это сделать сейчас? Пожалуйста, помогите мне, там много учебников, я тоже много смотрел, но не смог решить эту проблему.

Ответы [ 5 ]

2 голосов
/ 17 января 2012

Попробуйте это:

-(IBAction)readMessages:(id)sender {

    SecondView *secondView =[[SecondView alloc] initWithNibName:@"SecondView" bundle:nil];

    [self presentModalViewController:secondView animated:YES];    

  }

SecondView - это ваш подкласс UIViewController, который содержит UITableView.

1 голос
/ 18 января 2012

Q2: вы можете инициализировать ваши ячейки tableView с помощью JSONArray:

 (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    // Return the number of rows in the section.
    return [JSONarray count]; //***********
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) 
    {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];


       cell.textLabel.text = [JSONarray objectAtIndexIndexPath.row]; //***********
}
1 голос
/ 18 января 2012

Q1: Вам не нужно добавлять навигацию, чтобы вернуться на главную страницу.Когда вы когда-либо используете

[self.navigationController pushViewController:next animated:YES];

по умолчанию, в следующем представлении будет создана обратная навигация для возврата назад.

, если он еще не создан, попробуйте следующий код в следующемпросмотр:

- (void)viewDidLoad
{
    [super viewDidLoad];

    //To set the back buttin on leftside of Navigation bar
    UIBarButtonItem *backButton = [[[UIBarButtonItem alloc] initWithTitle:@"Back" style:UIBarButtonItemStyleDone target:self action:@selector(backclick:)] autorelease];
    self.navigationItem.leftBarButtonItem = backButton;

}

- (IBAction)backclick:(id)sender //first declrared in .h file
{
    // To goback to the previous view
    [self.navigationController popViewControllerAnimated:YES];
}
1 голос
/ 17 января 2012

Да, вы можете, попробуйте это для создания xib программно в viewDidload:

UIView *view1 = [[UIView alloc]initWithFrame:CGRectMake(10, 10,300,460)];
    view1.backgroundColor = [UIColor redColor];
    [self.view addSubview:view1];

Но лучше создать с помощью следующий путь в меню xcode:

Файл-> Новый -> Новый файл -> UIViewControllerSubClass -> Далее -> Далее -> Создать

Или просто перетащите вид из Ur Interface Builder

1 голос
/ 17 января 2012

Если у вас есть элемент управления навигацией, и если вы хотите нажать навигацию, попробуйте следующее:

-(IBAction)readMessages:(id)sender {
 NextView *next = [[NextView alloc]initWithNibName:@"NextView" bundle:nil];
        [self.navigationController pushViewController:next animated:YES];
        [next release];
}

, если у вас нет элемента управления навигацией, и если вы хотите просто отобразить следующий вид, попробуйте следующее:

-(IBAction)readMessages:(id)sender {

    NextView *next =[[NextView alloc] initWithNibName:@"NextView" bundle:nil];

    [self presentModalViewController:next animated:YES]; 
           [next release];
  }

если у вас есть подвид в том же классе, попробуйте следующее:

-(IBAction)readMessages:(id)sender {

      [self.view addsubview nextView];
      }
...