Prepareforsegue navigationItem.title落后

时间:2012-03-15 22:17:16

标签: objective-c xcode uitableview uinavigationitem

我仍然是对象c的新手,所以如果这是一个菜鸟问题,请跟我说。我正在尝试使用相应的对象信息设置我的navigationcontroller的标题。我正在使用prepareforsegue,但第一次是segue到新的控制器,标题是空白的。如果我再次尝试,它会显示,但如果我按下其他内容,它会显示我之前按下的内容的标题。我在下面嵌入了我的代码。

//.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

1 个答案:

答案 0 :(得分: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;
    }
}