iPhone Bookmark UIWebView - отображение заголовка страницы и сохранение URL - PullRequest
0 голосов
/ 23 июня 2011

У меня есть полнофункциональное приложение для веб-браузера, в котором хранятся страницы с закладками. При нажатии кнопки закладок отображается список сохраненных веб-сайтов. Вместо того, чтобы показывать URL, я бы хотел, чтобы в просмотре списка отображался заголовок страницы, но я бы хотел, чтобы UIWebView переходил по URL при нажатии на заголовок.

Я включил код ниже. Я также поместил свойства в оба заголовочных файла, но не могу заставить их работать. Пожалуйста, помогите!

ExplorerViewController.h

#import <UIKit/UIKit.h>

@interface ExplorerViewController : UIViewController <UITextFieldDelegate, UIWebViewDelegate, UIActionSheetDelegate>{
    UITextField *urlField;
    UIBarButtonItem *refreshButton;
    UIBarButtonItem *backButton;
    UIBarButtonItem *forwardButton;
    UIBarButtonItem *bookMarksButton;
    UIActivityIndicatorView *loadingActivity;
    UIWebView *webView;
    UINavigationBar *navigationBar;
}
@property (nonatomic, retain) IBOutlet UITextField *urlField;
@property (nonatomic, retain) IBOutlet UIBarButtonItem *refreshButton;
@property (nonatomic, retain) IBOutlet UIBarButtonItem *backButton;
@property (nonatomic, retain) IBOutlet UIBarButtonItem *forwardButton;
@property (nonatomic, retain) IBOutlet UIBarButtonItem *bookMarksButton;
@property (nonatomic, retain) IBOutlet UIActivityIndicatorView *loadingActivity;
@property (nonatomic, retain) IBOutlet UIWebView *webView;
@property (nonatomic, retain) IBOutlet UINavigationBar *navigationBar;
-(NSString*)repairURL:(NSString*)url;
-(IBAction)refreshWebView;
-(IBAction)goBack;
-(IBAction)goForward;
-(void)actualizeButtons;
-(IBAction)bookmarksButtonTapped;
-(IBAction)addBookmarkButtonTapped;
@end

ExplorerViewController.m

-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (buttonIndex == 0) {
        NSMutableArray *bookmarks = [[[NSUserDefaults standardUserDefaults] arrayForKey:@"Bookmarks"] mutableCopy];
        NSMutableArray *websitetitle = [[[NSUserDefaults standardUserDefaults] arrayForKey:@"Websitetitle"] mutableCopy];
        if (!bookmarks) {
            bookmarks = [[NSMutableArray alloc] init];
        }
        [bookmarks addObject:[[[[self webView]request] URL] absoluteString]];
        [websitetitle addObject:[self.webView stringByEvaluatingJavaScriptFromString:@"document.title"]];
        [[NSUserDefaults standardUserDefaults] setObject:bookmarks forKey:@"Bookmarks"];
        [[NSUserDefaults standardUserDefaults] setObject:websitetitle forKey:@"Websitetitle"];
        [bookmarks release];
        [websitetitle release];
    }
}

BookmarksViewController.h

#import <UIKit/UIKit.h>

@class ExplorerViewController;
@interface BookmarksViewController : UIViewController <UITableViewDelegate, UITableViewDataSource>{
    NSMutableArray *bookmarks;
    NSMutableArray *websitetitle;
    ExplorerViewController *explorerView;
}

@property (nonatomic, retain) NSMutableArray *bookmarks;
@property (nonatomic, retain) NSMutableArray *websitetitle;
@property (nonatomic, retain) ExplorerViewController *explorerView;

-(IBAction)cancelButtonTapped;

@end

BookmarksViewController.m

#import "BookmarksViewController.h"
#import "ExplorerViewController.h"

@implementation BookmarksViewController
@synthesize bookmarks, websitetitle, explorerView;


-(IBAction)cancelButtonTapped {
    [self.parentViewController dismissModalViewControllerAnimated:true];
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

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

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *cellIdentifier = @"Cell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier] autorelease];
    }

    cell.textLabel.text = [websitetitle objectAtIndex:indexPath.row];

    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    explorerView.urlField.text = [bookmarks objectAtIndex:indexPath.row];
    [explorerView textFieldShouldReturn:explorerView.urlField];
    [self.parentViewController dismissModalViewControllerAnimated:true];
}

-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        [bookmarks removeObjectAtIndex:indexPath.row];
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationFade];
        [[NSUserDefaults standardUserDefaults] setObject:bookmarks forKey:@"Bookmarks"];
    }
}

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

- (void)dealloc
{
    [super dealloc];
    // e.g. self.myOutlet = nil;
    [explorerView release];
    explorerView = nil;
    [bookmarks release];
    bookmarks = nil;
}

1 Ответ

0 голосов
/ 23 июня 2011

Вы должны реализовать tableView:didSelectRowAtIndexPath:, примерно так:

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{

  NSString *url=[bookmarks objectAtIndex:indexPath.row];

  // open url here

}

Несколько соображений по поводу вашего кода:

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

  explorerView.urlField.text = [bookmarks objectAtIndex:indexPath.row];
  [explorerView textFieldShouldReturn:explorerView.urlField];
  [self.parentViewController dismissModalViewControllerAnimated:true]; 

} 
  • Вы пытаетесь повторить Mobile Safari?
  • вам, вероятно, следует избегать сохранения ваших закладок в хранилище NSUserDefaults и использовать правильное хранилище.
  • вы не должны пытаться вызвать навигационное действие, имитируя события взаимодействия; правильный способ заставить UIWebView (ваш базовый объект браузера) загрузить веб-страницу, используя loadRequest:

Следующий код может работать на вас (здесь я полагаюсь на множество предположений):

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

  // Get your url from the bookmarks object
  NSString *urlString = [bookmarks objectAtIndex:indexPath.row];

  // Convert to a URL object.
  NSURL *url = [NSURL URLWithString:urlString];

 // Create request
 NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];

 //Load the request in the UIWebView.
 [explorerView.webView loadRequest:requestObj];

 // dismiss
 [self.parentViewController dismissModalViewControllerAnimated:true]; 

} 
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...