2012-03-15 55 views
1

我还是比较陌生的对象c,所以如果这是一个菜鸟问题,请耐心等待。我试图用相应的对象信息设置我的navigationcontroller的标题。我正在使用prepareforsegue,但第一次继续使用新控制器,标题为空。如果我再试一次,它会显示出来,但是如果我按下其他的东西,它会显示我以前按下的东西的标题。我在下面嵌入了我的代码。Prepare reforsegue navigationItem.title one behind

//.h 

#import <UIKit/UIKit.h> 

@interface STATableViewController : UITableViewController 

@property(strong,nonatomic)NSArray *listOfExercises; 
@property(weak,nonatomic)NSString *navTitle; 

@end 

//.m 

#import "STATableViewController.h" 
#import "ExercisesViewController.h" 

@implementation STATableViewController 

@synthesize listOfExercises = _listOfExercises, navTitle = _navTitle; 

- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 
    _listOfExercises = [NSArray arrayWithObjects:@"Raketstart",@"SpeedBåd",@"Træstamme",nil]; 
    self.navigationItem.title = @"Exercises";  
} 

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section 
{ 
    // Return the number of rows in the section. 
    return [_listOfExercises 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]; 
    } 

    NSString *cellValue = [_listOfExercises objectAtIndex:indexPath.row]; 
    cell.textLabel.text = cellValue; 

    return cell; 
} 

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    _navTitle = [_listOfExercises objectAtIndex:indexPath.row]; 
    //NSLog(_navTitle); 
} 

-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender 
{ 
    if([[segue identifier] isEqualToString:@"toExercise"]) 
    { 
     ExercisesViewController *foo = [segue destinationViewController]; 
     foo.navigationItem.title= _navTitle; 
    } 
} 

@end 

回答

5

发生这种情况的原因是prepareForSegue:sender:tableView didSelectRowAtIndexPath:之前被调用。因此,在使用所需值设置_navTitle属性之前,总是设置navigationItem的标题。

非但没有在didSelectRowAtIndex路径的称号,这样做在你的prepareForSegue这样的:

-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender 
{ 
    if([[segue identifier] isEqualToString:@"toExercise"]) 
    { 
     // "sender" is the table cell that was selected 
     UITableViewCell *cell = (UITableViewCell*)sender; 
     NSIndexPath *indexPath = [self.tableView indexPathForCell:cell]; 

     NSString *title= [_listOfExercises objectAtIndex:indexPath.row]; 

     ExercisesViewController *foo = [segue destinationViewController]; 
     foo.navigationItem.title = title; 
    } 
} 
+0

这工作,非常感谢你:) – 2012-03-15 23:04:34