передача данных из подробного представления в табличное представление ios 4

#iphone #uitableview #ios4

#iPhone #uitableview #ios4

Вопрос:

У меня есть два представления, первое (представление A) — это табличное представление. В каждой строке есть кнопка раскрытия, когда я нажимаю на кнопку, я отображаю второе представление (вид B), которое также является табличным представлением. Когда я нажимаю на строку, я хочу передать данные для просмотра A и отобразить их как detailTextLabel .

 #import <UIKit/UIKit.h>
@interface A : UIViewController <UITableViewDelegate, UITableViewDataSource> {
    NSDictionary *listData;
    NSArray *keys;
}
@property (nonatomic, retain) NSDictionary *listData;
@property (nonatomic, retain) NSArray *keys;
@end


#import "A.h"
@implementation A
@synthesize listData;
@synthesize keys;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)dealloc
{
    [listData release];
    [keys release];
    [super dealloc];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}

#pragma mark - View lifecycle

- (void)viewDidLoad 
{
    NSString *path = [[NSBundle mainBundle] pathForResource:@"Criteres" ofType:@"plist"];
    NSDictionary *dict = [[NSDictionary alloc] initWithContentsOfFile:path];
    self.listData = dict; 
    [dict release];
    NSArray *array = [[listData allKeys]sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)];
    self.keys = array;
    [super viewDidLoad];
}

- (void)viewDidUnload
{
    self.listData = nil;
    self.keys = nil;
    [super viewDidUnload];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

#pragma mark - 
#pragma mark Table View Data Source Methods

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView 
{ 
    return [keys count];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section 
{
    NSString *key = [keys objectAtIndex:section]; 
    NSArray *nameSection = [listData objectForKey:key]; 
    return [nameSection count];
}

-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section 
{
    NSString *key = [keys objectAtIndex:section]; 
    return key;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{
    NSUInteger section = [indexPath section]; 
    NSUInteger row = [indexPath row];
    NSString *key = [keys objectAtIndex:section]; 
    NSArray *nameSection = [listData objectForKey:key];
    static NSString *SectionsTableIdentifier = @"SectionsTableIdentifier";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:SectionsTableIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:SectionsTableIdentifier] autorelease];
    }

    cell.textLabel.text = [nameSection objectAtIndex:row]; 
    if (section == 0) {
        cell.accessoryType = UITableViewCellAccessoryDetailDisclosureButton;
        if (row == 2)
            cell.detailTextLabel.text = @"En m2";
        if (row == 1)
            cell.detailTextLabel.text = @"En €";
    }

    if (section == 1) {
        cell.accessoryType = UITableViewCellAccessoryDetailDisclosureButton;
        }
    }   
    return cell;
}

#pragma mark - 
#pragma mark Table Delegate Methods

- (NSInteger)tableView:(UITableView *)tableView indentationLevelForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSUInteger row = 2; 
    return row;
}

-(NSIndexPath *)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    return indexPath;
    }

- (void)tableView:(UITableView *)tableView accessoryButtonTappedForRowWithIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *ownerCell = [tableView cellForRowAtIndexPath:indexPath];
    if ([ownerCell.textLabel.text isEqualToString:@"Ecole"]) {
        B *prixview = [[B alloc]init];
        [self.navigationController pushViewController:prixview animated:YES];
        prixview.title = @"prix";
    }
    if ([ownerCell.textLabel.text isEqualToString:@"Crèche"]) {
        B *prixview = [[B alloc]init];
        [self.navigationController pushViewController:prixview animated:YES];
        prixview.title = @"Prix";
    }
}
@end



#import <UIKit/UIKit.h>
@interface B : UIViewController <UITableViewDelegate, UITableViewDataSource> {
    NSArray *typetab;
    NSInteger radioSelectionTypeBien;
    NSString *radioSelectionTypeBienString;
}
@property (nonatomic, retain) NSArray *typetab;
@property (nonatomic, retain) NSString *radioSelectionTypeBienString;
@end


#import "B.h"
@implementation B
@synthesize typetab;
@synthesize radioSelectionTypeBienString;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)dealloc
{
    [self.radioSelectionTypeBienString release];
    [self.typetab release];
    [super dealloc];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    UIBarButtonItem *backButton = [[UIBarButtonItem alloc]
                                 initWithTitle:@"Critères" 
                                 style:UIBarButtonItemStyleBordered
                                 target:self
                                 action:@selector(backButtonActionTypeBien:)];
    self.navigationItem.leftBarButtonItem = backButton;
    [backButton release];
    radioSelectionTypeBien = -1;
    NSArray *type = [[NSArray alloc]initWithObjects:@"Appartement",@"Maison",@"Commerce", nil ];
    self.typetab = type;
    [type release];
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
}

-(IBAction)backButtonActionTypeBien: (id)sender
{
    [self.navigationController pushViewController:self.navigationController.parentViewController animated:YES];
}

- (void)viewDidUnload
{
    self.radioSelectionTypeBienString = nil;
    self.typetab = nil;
    [super viewDidUnload];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

#pragma mark - 
#pragma mark Table View Data Source Methods 

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section 
{ 
    return [self.typetab count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{
    static NSString *SimpleTableIdentifier = @"SimpleTableIdentifier";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:SimpleTableIdentifier];
    if (cell == nil) { cell = [[[UITableViewCell alloc]
                                initWithStyle:UITableViewCellStyleDefault reuseIdentifier:SimpleTableIdentifier] autorelease];
    }
    cell.accessoryType = UITableViewCellAccessoryNone;
    cell.textLabel.text = [typetab objectAtIndex:indexPath.row];
    if (indexPath.row == radioSelectionTypeBien){ 
        cell.accessoryType = UITableViewCellAccessoryCheckmark;
    }
    return cell;
}

#pragma mark -
#pragma mark Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath 
{
    radioSelectionTypeBien = indexPath.row;
    radioSelectionTypeBienString = [tableView cellForRowAtIndexPath:indexPath].textLabel.text;
    [tableView reloadData];
}
@end
  

Ответ №1:

Обычно я пишу метод в контроллере B , например:

 -(voi)initVCwithString:(NSString*)_string andSomeObject:(NSObject *)_obj;
  

(таким образом, контроллер B должен иметь 2 ивара, строку и объект, которые вы должны установить в этом методе)

затем вызовите это в вашем didSelectRowAtIndexPath : из контроллера A

 ...
B _vcB=//alloc..init..etc
[_vcB initVCwithString:yourCell.textLabel.text andSomeObject:someObj];
[self.navigationController pushViewController:_vcB animated:YES];
[_vcB release];
  

Затем в cellForRowAtIndexPath of B set cell.detailTextLabel.text=yourStringIvar;

Надеюсь, это поможет.

Ответ №2:

В принципе, есть две возможности, которые кажутся подходящими. Вы можете написать пользовательский метод делегирования, который передает значение контроллеру A, или вы можете отправить уведомление через центр уведомлений, который затем может присвоить значение контроллеру A, перехватывая уведомление, которое будет вызвано выбором ячейки в контроллере B.