UIPageViewController - 每个页面显示不同的Webview

时间:2011-12-27 15:06:13

标签: xcode uiwebview uipageviewcontroller

我想知道如何在UIPageViewController不同UIWebView的URL的每个页面上显示,假设第一个pdf是one.pdf,第二个是two.pdf等......

我在Xcode 4.2中使用UIPageViewController

1 个答案:

答案 0 :(得分:3)

执行此操作的最佳方法是创建自定义viewController子类。

@interface WebViewController : UIViewController

- (id)initWithURL:(NSURL *)url frame:(CGRect)frame;

@property (retain) NSURL *url;

@end

在这个例子中,我调用了类WebViewController并为其提供了一个自定义初始化方法。 (还给它一个保存网址的属性)。

首先在你实现中你应该合成该属性

@implementation WebViewController

@synthesize url = _url;

同样在实现中你应该做这样的事情来创建你的init方法:

- (id)initWithURL:(NSURL *)url frame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        self.url = url;
    }
    return self;
}

记住你还需要(如果不使用ARC):

- (void)dealloc {
    self.url = nil;
    [super dealloc];
}

然后你还需要一个:

- (void)loadView {
    UIWebView *webView = [[UIWebView alloc] initWithFrame:self.view.bounds];
    [self.view addSubview:webView];
    NSURLRequest *request = [NSURLRequest requestWithURL:self.url];
    [webView loadRequest:request];
    [webView release]; // remove this line if using ARC

    // EDIT :You could add buttons that will be on all the controllers (pages) here
    UIButton *button1 = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    [button1 addTarget:self action:@selector(buttonTap) forControlEvents: UIControlEventTouchUpInside];
    [self.view addSubview:button1];
}

还记得你需要实现方法

- (void)buttonTap {
    // Do something when the button is tapped
}

// END EDIT

在具有UIPageViewController的主控制器中,您需要执行以下操作:

NSMutableArray *controllerArray = [NSMutableArray array];
for (NSUInteger i = 0; i < urlArray.count; i++) {
    WebViewController *webViewController = [[WebViewController alloc] initWithURL:[urlArray objectAtIndex:i]];
    [controllerArray addObject:webViewController];
// EDIT: If you wanted different button on each controller (page) then you could add then here
UIButton *button1 = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[button1 addTarget:self action:@selector(buttonTap) forControlEvents: UIControlEventTouchUpInside];
[webViewController.view addSubview:button1];
// In this case you will need to put the "buttonTap" method on this controller NOT on the webViewController. So that you can handle the buttons differently from each controller.
// END EDIT

[webViewController release]; // remove this if using ARC
}
pageViewController.viewControllers = controllerArray;

所以基本上,我们为你想要显示的每个页面创建了一个WebViewController类的实例,然后将它们全部添加为你的UIPageViewController的viewControllers数组,以便在页面之间进行分页。

假设urlArray是一个有效的NSArray,包含要加载的所有页面的NSURL对象,并且您已经创建了一个UIPageViewController并将其添加到视图层次结构中,那么这应该可以解决问题。

希望这有帮助,如果您需要任何澄清或进一步的帮助,请告诉我:)