2012-01-29 1 views
1

Я таблица основаны от Сэма Самоучитель IOS РазвитиеFlowerViewController, что под didSelectRowAtIndesPath он идет на веб-сайт в новом СИБЕ (я отлажен частью данные передачи). МОЙ ВОПРОС: Я хотел бы обновить это, вместо того, чтобы идти к нибу, чтобы перейти в раскадровку. Я знаю, что вместо того, чтобы использовать didSelectRow ... Я использую prepareForSegue ... но я не могу выяснить подробности ...передать данные из таблицы в WebView С ИСПОЛЬЗОВАНИЕМ перетекает

мой меня ViewController.m следующим:

- (void)viewDidLoad { 
    [self movieData]; 
    [super viewDidLoad]; 

    self.title = @"Movies"; 

    // Uncomment the following line to display an Edit button in the navigation bar for this view controller. 
    // self.navigationItem.rightBarButtonItem = self.editButtonItem; 
} 


#pragma mark - 
#pragma mark Table view data source 

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


// Customize the number of rows in the table view. 
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { 
    return [[movieData objectAtIndex:section] count]; 
} 


// Customize the appearance of table view cells. 
- (UITableViewCell *)tableView:(UITableView *)tableView 
     cellForRowAtIndexPath:(NSIndexPath *)indexPath { 

    static NSString *CellIdentifier = @"Cell"; 

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

    // Configure the cell. 

    [[cell textLabel] 
    setText:[[[movieData 
       objectAtIndex:indexPath.section] 
       objectAtIndex: indexPath.row] 
       objectForKey:@"name"]]; 

    [[cell imageView] 
    setImage:[UIImage imageNamed:[[[movieData 
            objectAtIndex:indexPath.section] 
            objectAtIndex: indexPath.row] 
            objectForKey:@"picture"]]]; 

    [[cell detailTextLabel] 
    setText:[[[movieData 
       objectAtIndex:indexPath.section] 
       objectAtIndex: indexPath.row] 
       objectForKey:@"detail"]]; 
    cell.detailTextLabel.numberOfLines = 0; 

    cell.accessoryType=UITableViewCellAccessoryDisclosureIndicator; 
    return cell; 
} 


// Override to support row selection in the table view. 
- (void)tableView:(UITableView *)tableView 
didSelectRowAtIndexPath:(NSIndexPath *)indexPath { 

    WebViewController *webViewController = 
    [[WebViewController alloc] initWithNibName: 
    @"WebViewController" bundle:nil]; 

    webViewController.detailURL= 
    [[NSURL alloc] initWithString: 
    [[[movieData objectAtIndex:indexPath.section] objectAtIndex: 
     indexPath.row] objectForKey:@"url"]]; 

    webViewController.title= 
    [[[movieData objectAtIndex:indexPath.section] objectAtIndex: 
     indexPath.row] objectForKey:@"name"]; 

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

} 


#pragma mark - 
#pragma mark Table view delegate 



#pragma mark - 
#pragma mark Memory management 

- (void)didReceiveMemoryWarning { 
    // Releases the view if it doesn't have a superview. 
    [super didReceiveMemoryWarning]; 

    // Relinquish ownership any cached data, images, etc that aren't in use. 
} 

- (void)viewDidUnload { 
    // Relinquish ownership of anything that can be recreated in viewDidLoad or on demand. 
    // For example: self.myOutlet = nil; 
} 


- (void)movieData { 

    NSMutableArray *myMovies; 

    movieSections=[[NSMutableArray alloc] initWithObjects: 
        @"Movies",nil]; 

    myMovies=[[NSMutableArray alloc] init]; 

    [myMovies addObject:[[NSMutableDictionary alloc] 
          initWithObjectsAndKeys:@"Movie1",@"name", 
          @"1.png",@"picture", 
          @"http://www.url1.com",@"url",@"Some information",@"detail",nil]]; 
    [myMovies addObject:[[NSMutableDictionary alloc] 
          initWithObjectsAndKeys:@"Movie2",@"name", 
          @"2.png",@"picture", 
          @"http://www.url2.com",@"url",@"Some information 2",@"detail",nil]]; 
    [myMovies addObject:[[NSMutableDictionary alloc] 
          initWithObjectsAndKeys:@"Movie3",@"name", 
          @"3.png",@"picture", 
          @"http://www.url3.com",@"url",@"Some information 3",@"detail",nil]]; 
    [myMovies addObject:[[NSMutableDictionary alloc] 
          initWithObjectsAndKeys:@"Movie4",@"name", 
          @"4.png",@"picture", 
          @"http://www.url4.com",@"url",@"Some information 4",@"detail",nil]]; 

    movieData=[[NSMutableArray alloc] initWithObjects: 
       myMovies,nil]; 
} 

Я попытался закомментируйте didSelectRowAtIndexPath и добавьте следующий за Segue, но клеточные моменты и ничего не происходит (к счастью, он не замерзает/аварии, но нет ничего положительного)

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender { 

    if ([[segue identifier] isEqualToString:@"movieSegue"]) { 

     NSIndexPath *selectedRowIndex = [self.tableView indexPathForSelectedRow]; 
     WebViewSegue *_webViewSegue = [segue destinationViewController]; 
     _webViewSegue.detailURL = 
     [[NSURL alloc] initWithString:[[[movieData objectAtIndex:selectedRowIndex.section] objectAtIndex: 
             selectedRowIndex.row] objectForKey:@"url"]]; 
    } 
} 

Тогда я хочу, чтобы перейти к WebViewSegue

WebViewSegue.h:

@interface WebViewSegue : UIViewController { 
    IBOutlet UIWebView *detailWebView; 
    NSURL *detailURL; 
    IBOutlet UIActivityIndicatorView *activity; 
    NSTimer *timer; 
} 

@property (nonatomic, weak) NSURL *detailURL; 
@property (nonatomic, weak) UIWebView *detailWebView; 
@property (nonatomic, weak) UIActivityIndicatorView *activity; 

@end 

WebViewSegue.m:

@synthesize detailWebView =_detailWebView; 
@synthesize detailURL = _detailURL; 
@synthesize activity =_activity; 

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

- (void)didReceiveMemoryWarning 
{ 
    // Releases the view if it doesn't have a superview. 
    [super didReceiveMemoryWarning]; 

    // Release any cached data, images, etc that aren't in use. 
} 

#pragma mark - View lifecycle 


- (void)viewDidLoad { 
    [super viewDidLoad]; 

    [detailWebView loadRequest:[NSURLRequest requestWithURL:detailURL]]; 

    timer = [NSTimer scheduledTimerWithTimeInterval:(1.0/2.0) 
              target:self 
              selector:@selector(tick) 
              userInfo:nil 
              repeats:YES]; 
} 

-(void)tick { 
    if (!detailWebView.loading) 
     [activity stopAnimating]; 
    else 
     [activity startAnimating]; 

} 


- (void)viewDidUnload 
{ 
    [super viewDidUnload]; 
    // Release any retained subviews of the main view. 
    // e.g. self.myOutlet = nil; 
} 

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation 
{ 
    // Return YES for supported orientations 
    return (interfaceOrientation == UIInterfaceOrientationPortrait); 
} 

-(void)wevView:(UIWebView *)webView didFailLoadWithError:(NSError *)error 
{ 
    UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"Cannot connect" 
                message:@"Please check your connection and try again" 
                delegate:nil 
              cancelButtonTitle:@"OK" 
              otherButtonTitles:nil]; 
    [alert show]; 
} 

@end 

ответ

0

Я ответил на ваш вопрос в другом посте на сайте. См. Мой ответ here.

В частности, о том, как передать данные из таблицы в следующую серию раскадров, сначала создайте свойство для данных в следующем расписании (например, контроллер представления). Затем установите это свойство в методе prepareForSegue таблицы (контроллер представления исходного кода).

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender 
{ 
    // needed if you have multiple segues 
    if ([[segue identifier] isEqualToString:@"changeNameAndDate"]) 
    { 
     [[segue destinationViewController] setDataProperty:self.tableData]; 
     // where dataProperty is the property in the designation view controller 
     // and tableData is the data your are passing from the source 
    { 
} 
+0

Спасибо за попытку, но я думаю, что ваш ответ о том, как обращаться с перьями; мой вопрос, однако, касается передачи данных из таблицы в следующий сериал раскадровки. Любые другие мысли о коде? – SnowboardBruin

+0

См. Обновление в ответе, объясняющем prepareForSegue –

0

Это много кода, чтобы переварить; вы должны попытаться упростить. Но если я правильно прочитал, ваш базовый подход кажется правильным.

Сначала поставьте точку останова на prepareForSegue:sender: и убедитесь, что она вызвана, и что идентификатор - это то, что вы ожидаете от нее.

Затем поставьте точку останова на viewDidLoad и убедитесь, что она называется, когда вы думаете, что это должно быть.

Я бы вытащил loadRequest: в свой собственный метод и назвал его как в viewDidLoad, так и в setDetailURL:. Вероятно, setDetailURL: вызывается после viewDidLoad, если все это находится в одном раскадровке.


EDIT То, что я хочу сказать, что prepareForSegue:sender: вероятно правильно. Проблема в представленном контроллере представления.

- (void)reloadWebView { // Pull the loadRequest: out... 
    [self.detailWebView loadRequest:[NSURLRequest requestWithURL:self.detailURL]]; 
} 

- (void)viewDidLoad { 
    [super viewDidLoad]; 
    [self reloadWebView]; // ...and call it both in viewDidLoad... 
    ... 
} 

- (void)setDetailURL:(NSURL *)URL { 
    [URL retain]; 
    [detailURL release]; 
    detailURL = URL; 
    [self reloadWebView]; // ...and in setDetailURL: 
} 

Также обратите внимание, что для вашего таймера нет причин. Просто включите индикатор прогресса в reloadWebView и выключите его в webViewDidFinishLoad и webView:didFailLoadWithError:. Ваш текущий подход делает невозможным освобождение этого контроллера просмотра, потому что таймер сохраняет его навсегда.

+0

Благодарим вас за то, что вы сказали, что я могу быть прав в своей попытке ... но можете ли вы взять удар по коду, чтобы заполнить prepareForSegue? Благодаря! Я действительно не уверен, что означало с вытаскиванием loadRequest в свой собственный метод ... не уверен, что бы я вложил внутрь этого метода ... – SnowboardBruin

+0

@ms вы поставили точки останова, как было предложено @rob? Каковы были результаты. –

Смежные вопросы