0

我一直在为 iPhone/iPad 设备开发这个项目,在完成项目的 iPhone 部分后,我受到了改变 iPad 项目风格的灵感。

我的场景:

我有一个视图,其中包含链接到网站的 UIButtons。最初我计划这些按钮使用 Push 序列打开单独的 View,其中已经有一个 UIWebView 来打开网页。但后来我想也许我可以使用 UIButtons 在父视图中打开所需的网页。

我的问题:

是否可以使用 UIButton 加载网页,但在与用于加载网页的 UIButton 位于同一视图中的 UIWebView 中?

在此先感谢大家,我认为这应该是可能的,但目前还没有想到。

4

1 回答 1

1

当然是可能的(真的......为什么不呢?)。你只有一个UIView有一个UIWebView和几个UIButton子视图。然后你可以做这样的事情:

// Suppose that self.mainView is the main container (and an IBOutlet)
// and self.webView is the UIWebView (also an IBOutlet)
// and of course your UIButtons (connected to IBActions)

-(IBAction)visitSiteA:(id)sender
{
    NSString *urlAddress = @”http://www.siteA.com”;

    //Create a URL object.
    NSURL *url = [NSURL URLWithString:urlAddress];

    //URL Request Object
    NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];

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

-(IBAction)visitSiteB:(id)sender
{
    NSString *urlAddress = @”http://www.siteB.com”;

    //Create a URL object.
    NSURL *url = [NSURL URLWithString:urlAddress];

    //URL Request Object
    NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];

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

现在,如果您不使用 InterfaceBuilder,您可以在代码中构建您的 webView 和按钮,然后将它们添加到您的 mainView。

最后,如果您计划有很多按钮,您可以通过将加载部分分解为一个单独的方法来优化代码,并只需从您的 IBActions 传递 url。像这样的东西:

-(void)loadUrlAddress:(NSString *)urlAddress
{
    //Create a URL object.
    NSURL *url = [NSURL URLWithString:urlAddress]; 

    //URL Request Object
    NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];

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

-(IBAction)visitSiteA:(id)sender
{
    [self loadUrlAddress:@"http://www.siteA.com"];
}
于 2012-07-11T18:32:25.907 回答