问题
I am trying to learn Xcode by making a simple app. But I been looking on the net for hours (days) and I cant figure it out how I make a button that open a UIWebView in another ViewController :S
first let me show you some code that I have ready:
I have a few Buttons om my main Storyboard that each are title some country codes like UK, CA and DK.
When I press one of those Buttons I have an IBAction like this:
- (IBAction)ButtonPressed:(UIButton *)sender {
// Google button pressed
NSURL* allURLS;
if([sender.titleLabel.text isEqualToString:@"DK"]) {
// Create URL obj
allURLS = [NSURL URLWithString:@"http://google.dk"];
}else if([sender.titleLabel.text isEqualToString:@"US"])
{
allURLS = [NSURL URLWithString:@"http://google.com"];
}else if([sender.titleLabel.text isEqualToString:@"CA"])
{
allURLS = [NSURL URLWithString:@"http://google.ca"];
}
NSURLRequest* req = [NSURLRequest requestWithURL:allURLS];
[myWebView loadRequest:req];
}
How do I make this open UIWebview on my other Viewcontroller named myWebView?
please help a lost man :D
回答1:
Well, you've firstViewController already designed and coded, now you've to create secondViewController with a UIWebView
binded in IB
it self, also it have a setter NSString
variable like strUrl
that you need to pass at the time of pushing or presenting secondViewController, and assign it to UIWebView
in viewDidLoad
of secondViewController. See my answer about how to pass a NSString? Also UIWebView
has its delegates method (What's delegate & datasource methods? - Apple Doc) Which you can use to handle URL
request.
These are the delegate
of UIWebView
, if you'll going to use it, you need to give UIWebView
delegate to self
.
- (void)webViewDidStartLoad:(UIWebView *)webView;
- (void)webViewDidFinishLoad:(UIWebView *)webView;
- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error;
回答2:
firstViewController.m
- (IBAction)ButtonPressed:(UIButton *)sender {
NSURL* allURLS;
//get your URL
secondViewControlelr *secondView=[[secondViewControlelr alloc]init];
second.urlToLoad=allURLS;
[self.navigationController pushViewController:secondView animated:YES];
}
secondViewControlelr.h //declare url and set property
NSURL *urlToLoad;
secondViewControlelr.m
- (void)viewDidLoad
{
myWebView=[[UIWebView alloc]initWithFrame:CGRectMake(0, 0, 320, 460)];
[self.view addSubview:myWebView];
NSURLRequest *urlReq=[NSURLRequest requestWithURL:self.urlToLoad cachePolicy:NSURLCacheStorageNotAllowed timeoutInterval:10];
[myWebView loadRequest:urlReq];
}
来源:https://stackoverflow.com/questions/13208247/press-a-button-and-open-a-url-in-another-viewcontroller