2015-03-24 3 views
0

Доброго дня,SEGUE не обновляется внутри TableViewController

Я создал SEGUE в моем TableViewController, где пользователь может коснуться профилем пользователя и отправляет это имя пользователя в ProfileViewController, где загружается информация о пользователе (сообщения, изображения , info ...) (что-то вроде стены Facebook).

Проблема заключается в том, что я касаюсь одного пользователя, он отображает все правильно, но когда я касаюсь другого изображения профиля, он снова отображает тот же ProfileViewController, что и имя пользователя не обновляется, и оно отправляется неправильно.

Когда я касаюсь в любом месте экрана, а затем снова касаюсь профиля пользователя, в этом случае он работает, но мне нужно сделать эту работу в каждом случае.

Я собираюсь отправить мой TableViewController, если это поможет вам найти проблему, потому что это почти работает, единственное, что мне нужно, чтобы исправить это, что имя пользователя, которое не обновляется (Tap Gesture распознавателя над изображением) ,

Сегменты находятся в конце кода.

TableViewController.m

// 
// CarTableViewController.m 
// 

#import "CarTableViewController.h" 
#import "CarTableViewCell.h" 
#import "CarTableViewController.h" 
#import "CarDetailViewController.h" 
#import "OtherProfileUserViewController.h" 
#import <SDWebImage/UIImageView+WebCache.h> 

@implementation CarTableViewController 

@synthesize carMakes = _carMakes; 
@synthesize carModels = _carModels; 
@synthesize carImages = _carImages; 

@synthesize likes = _likes; 
@synthesize comments = _comments; 
@synthesize username = _username; 
@synthesize refuser = _refuser; 
@synthesize profileImage = _profileImage; 

- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 

    [self fetchJson]; 

    [self.tableView reloadData]; 

    // Initialize the refresh control. 
    self.refreshControl = [[UIRefreshControl alloc] init]; 
    //self.refreshControl.backgroundColor = [UIColor blackColor]; 
    //self.refreshControl.tintColor = [UIColor whiteColor]; 
    [self.refreshControl addTarget:self 
          action:@selector(fetchJson) 
        forControlEvents:UIControlEventValueChanged]; 
} 

- (void)viewWillAppear:(BOOL)animated 
{ 
    self.navigationController.navigationBar.hidden = YES; 
} 

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView 
{ 
    // Return the number of sections. 
    return 1; 
} 


- (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 = @"carTableCell"; 

    CarTableViewCell *cell = [tableView 
           dequeueReusableCellWithIdentifier:CellIdentifier]; 

    if (cell == nil) { 
     cell = [[CarTableViewCell alloc] 
       initWithStyle:UITableViewCellStyleDefault 
       reuseIdentifier:CellIdentifier]; 
    } 

    // Configure the cell... 
    cell.makeLabel.text = [[_jsonArray objectAtIndex:indexPath.row] valueForKey:@"id"]; 
    cell.likes.text = [[_jsonArray objectAtIndex:indexPath.row] valueForKey:@"likes"]; 
    cell.comments.text = [[_jsonArray objectAtIndex:indexPath.row] valueForKey:@"comments"]; 
    cell.username.text = [[_jsonArray objectAtIndex:indexPath.row] valueForKey:@"username"]; 
    cell.refuser.text = [[_jsonArray objectAtIndex:indexPath.row] valueForKey:@"user_ref"]; 

    cell.modelLabel.text = [[_jsonArray objectAtIndex:indexPath.row] valueForKey:@"user"]; 

    NSURL * imageURL = [NSURL URLWithString:[[_jsonArray objectAtIndex:indexPath.row] valueForKey:@"imagen"]]; 

    [cell.carImage setImageWithURL:imageURL placeholderImage:[UIImage imageNamed:@"imagen"] options:SDWebImageRefreshCached]; 

    NSURL * imageURL2 = [NSURL URLWithString:[[_jsonArray objectAtIndex:indexPath.row] valueForKey:@"image"]]; 

    [cell.profileImage setImageWithURL:imageURL2 
         placeholderImage:[UIImage imageNamed:@"image"] 
          options:SDWebImageRefreshCached]; 

    return cell; 
} 

-(void)fetchJson { 

    self.carModels = [[NSMutableArray alloc] init]; 
    self.carMakes = [[NSMutableArray alloc] init]; 
    self.carImages = [[NSMutableArray alloc] init]; 
    self.likes = [[NSMutableArray alloc] init]; 
    self.comments = [[NSMutableArray alloc] init]; 

    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); 
    dispatch_async(queue, ^{ 

     NSString * urlString = [NSString stringWithFormat:@"http://website.com/service.php"]; 
     NSURL * url = [NSURL URLWithString:urlString]; 
     NSData * data = [NSData dataWithContentsOfURL:url]; 

     NSError *error; 
     [_jsonArray removeAllObjects]; 
     _jsonArray = [NSJSONSerialization 
         JSONObjectWithData:data 
         options:NSJSONReadingMutableContainers|NSJSONReadingMutableLeaves 
         error:&error]; 


      for(int i=0;i<_jsonArray.count;i++) 
      { 
       NSDictionary * jsonObject = [_jsonArray objectAtIndex:i]; 
       NSString* imagen = [jsonObject objectForKey:@"imagen"]; 
       [_carImages addObject:imagen]; 

       NSDictionary * jsonObject2 = [_jsonArray objectAtIndex:i]; 
       NSString* user = [jsonObject2 objectForKey:@"user"]; 
       [_carMakes addObject:user]; 

       NSDictionary * jsonObject3 = [_jsonArray objectAtIndex:i]; 
       NSString* date = [jsonObject3 objectForKey:@"date"]; 
       [_carModels addObject:date]; 
      } 
     NSLog(@"carModels ==> %@", _jsonArray); 

     dispatch_async(dispatch_get_main_queue(), ^{ 
      { 
       [self.tableView reloadData]; 
       [self.refreshControl endRefreshing]; 
      }}); 

     } 
    ); 
} 

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender { 
    if ([segue.identifier isEqualToString:@"segueprofile"]) { 
     NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow]; 
     OtherProfileUserViewController *destViewController = segue.destinationViewController; 
     destViewController.recipeName = [[_jsonArray objectAtIndex:indexPath.row] valueForKey:@"username"]; 
    } 
    if ([segue.identifier isEqualToString:@"segueprofile2"]) { 
     NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow]; 
     OtherProfileUserViewController *destViewController = segue.destinationViewController; 
     destViewController.recipeName = [[_jsonArray objectAtIndex:indexPath.row] valueForKey:@"username"]; 
    } 
} 

@end 

Спасибо заранее.

+0

Я кажется selectedRow, возможно, не обновляется. вы можете использовать отправителя для поиска строки и получения данных. – SolaWing

+0

Я бы предпочел использовать метод делегирования didSelectRowAtIndexPath и вручную выполнить отступ от него. Эта последовательность кажется мне более стабильной – heximal

+0

Привет @heximal, можете ли вы показать мне пример? Я довольно новичок в Objective-C, и я не знаю, как делать то, что вы говорите. Очень признателен. – BBangF1

ответ

0

ОК, вот один из вариантов. 1. Удалите все существующие segues (segueprofile и segueprofile2) 2. Подключите свой монитор tableviewcontroller (важно: не к табло, а к самому контроллеру) с контроллером деталей, нажав на кнопку -segue и назовите его segueprofile3 3. Скомпонуйте свой код следующим образом:

@property (nonatomic, strong) NSIndexPath * selectedIndexPath; 

... 

- (void)tableView:(UITableView *)aTableView didSelectRowAtIndexPath:(NSIndexPath *)anIndexPath { 
    self.selectedIndexPath = anIndexPath; 
    [self performSegueWithIdentifier:@"segueprofile3" sender:nil]; 
} 

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender { 
    if ([segue.identifier isEqualToString:@"segueprofile3"]) { 
     OtherProfileUserViewController *destViewController = segue.destinationViewController; 
     destViewController.recipeName = [[_jsonArray objectAtIndex:selectedIndexPath.row] valueForKey:@"username"]; 
    } 
} 
+0

Благодаря @heximal, это означает, что когда я нажимаю на полную строку (не только на изображение профиля), вы начнете Segue в ProfileViewController? Мне нужно, чтобы это работало только на профиле изображения (а также на имени изображения), потому что у меня уже есть segue, используя жест жесткости строки (он открывает эту «запись» с дополнительной информацией). – BBangF1

+0

ОК, это не проблема, большая часть этого кода и изменения IB остаются актуальными. Все, что вам нужно, это обработать нажатие на UIImageView и запустить один и тот же сеанс. Если у вас простая структура с плоскими таблицами, вы можете связать UIImageView с indexPath с помощью свойства tag, которое является целым числом, вы можете назначить его при создании TableCell – heximal

+0

. Я собираюсь попробовать то, что вы говорите, но немного поможет, потому что как я уже сказал вам, я не эксперт, и сейчас все очень сложно для меня. Можете ли вы показать мне пример с тем, что вы говорите? Еще раз спасибо @heximal – BBangF1

0

Другой вариант. Поместите UIButton прямо над аватаром UIImageView. Создайте соответствующий IBOutlet внутри вашего класса CarTableViewCell и выполните выходное соединение.

@property (nonatomic, weak) UIButton * btnAvatar; 

Далее изменить CarTableViewController код

//1. declare new propery 
@property (nonatomic, strong) id selectedProfile; 

//2. implement future button tap handler 
-(IBAction) btnAvatarDidPress:(id) sender { 
    int tag = ((UIButton *) sender).tag; 
    self.selectedProfile = [_jsonArray objectAtIndex:tag]; 
    [self performSegueWithIdentifier:@"segueprofile3" sender:nil]; 
} 


//Extend your cellForRowAtIndexPath method 
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    static NSString *CellIdentifier = @"carTableCell"; 

    CarTableViewCell *cell = [tableView 
           dequeueReusableCellWithIdentifier:CellIdentifier]; 

    if (cell == nil) { 
     cell = [[CarTableViewCell alloc] 
       initWithStyle:UITableViewCellStyleDefault 
       reuseIdentifier:CellIdentifier]; 
    } 

    // Configure the cell... 
    cell.makeLabel.text = [[_jsonArray objectAtIndex:indexPath.row] valueForKey:@"id"]; 
    cell.btnAvatar.tag = indexPath.row; 
... rest of method 
} 

затем удалить метод didSelectRowAtIndexPath и подключить действие btnAvatar Touch Up Inside на метод btnAvatarDidPress внутри кода контроллера. Надеюсь, я ничего не забыл.

0

вот ваш пример, в prepareForSegue, получить ячейку кнопки, которая находится в:

id v = sender; 
while (![(v= v.superView) isKindOfClass:[UITableViewCell class]] 
     && v!=nil) ; 
if (v==nil) 
    // no ancestor view is cell. 
else{ 
    // now v is the cell. 
    NSIndexPath * indexPath = [self.tableView indexPathForCell:v]; 
    // do the left 
} 
Смежные вопросы