0

iOS 用の Web ブラウザー アプリをプログラミングしていて、問題に遭遇しました。最初は、検索テキスト フィールドと Web ビューが同じビューにありました (すべて問題ありませんでした :)。Web ビューを別のビューに配置すると、Web ビューはページをロードせず、空白のままになります。したがって、問題は、Web ビューが別のビューに読み込まれないことです (テキスト フィールドと Web ビューが同じビューにある場合に機能します)。

私のコード:

#import "ViewController.h"
#import <QuartzCore/QuartzCore.h>

@interface ViewController ()

@end

@implementation ViewController

@synthesize searchButton;




- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib

}


-(IBAction)SearchButton:(id)sender {
    NSString *query = [searchField.text stringByReplacingOccurrencesOfString:@" " withString:@"+"];
    NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"http://www.google.com/search?q=%@", query]];
                                       NSURLRequest *request = [NSURLRequest requestWithURL:url];
                                       [webView loadRequest:request];

    ViewController *WebView = [self.storyboard instantiateViewControllerWithIdentifier:@"WebView"];
    [self presentViewController:WebView animated:YES completion:nil];
  }


- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [self.view endEditing:YES];
}


- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
4

1 に答える 1

1

SearchButton メソッドは現在のクラスの webView を参照しますが、表示されようとしているのは新しい ViewController (WebView と呼びます) であり、UIWebView を含む必要があります。したがって、提示されたView ControllerのUIWebViewはloadRequestに到達しません。

UIViewController のサブクラスを作成して、Web ビューを含めます。(MyWebViewController のように呼びます) urlString というプロパティが必要です。現在ストーリーボードに描画しているビュー コントローラーのクラスを MyWebViewController に変更してください。

SearchButton メソッドは次のようになります。

// renamed to follow convention
- (IBAction)pressedSearchButton:(id)sender {

    NSString *query = [searchField.text stringByReplacingOccurrencesOfString:@" " withString:@"+"];
    NSString *urlString = [NSString stringWithFormat:@"http://www.google.com/search?q=%@", query];

    // remember to change the view controller class in storyboard
    MyWebViewController *webViewController = [self.storyboard instantiateViewControllerWithIdentifier:@"WebView"];

    // urlString is a public property on MyWebViewController
    webViewController.urlString = urlString;
    [self presentViewController:webViewController animated:YES completion:nil];
}

新しいクラスは、urlString からのリクエストを形成できます...

// MyWebViewController.h
@property (nonatomic, strong) NSString *urlString;
@property (nonatomic, weak) IBOutlet UIWebView *webView;  // be sure to attach in storyboard

// MyWebViewController.m

- (void)viewWillAppear:(BOOL)animated {

    [super viewWillAppear:animated];

    NSURL *url = [NSURL URLWithString:self.urlString];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    [self.webView loadRequest:request];
}
于 2013-06-19T06:09:03.670 に答える