我在我的应用中嵌入了PDF列表。我想使用webView一次显示一个pdf,从表视图控制器中选择。来自Neil Smith的示例程序使用webView使用详细视图控制器中的以下代码片段显示网页:
if let address = webSite {
let webURL = NSURL(string: address)
let urlRequest = NSURLRequest(URL: webURL!)
webView.loadRequest(urlRequest)
以下代码段执行我想要的操作,但仅适用于文件" TestPDF"
if let pdf = NSBundle.mainBundle().URLForResource("TestPDF", withExtension: "pdf",
subdirectory: nil, localization: nil) {
let req = NSURLRequest(URL: pdf)
let webView = UIWebView(frame: CGRectMake(20,20,self.view.frame.size.width-40,self.view.frame.size.height-40))
webView.loadRequest(req)
self.view.addSubview(webView)
我想更改此选项,以便从列表中选择PDF,例如:
pdfAddresses = [
"TestPDF.pdf",
"TestPDF2.pdf",
"TestPDF3.pdf",
"TestPDF4.pdf",
"testPDF5.pdf"]
segue代码适用于webAddress列表:
if segue.identifier == "ShowAttractionDetails" {
let detailViewController = segue.destinationViewController
as! AttractionDetailViewController
let myIndexPath = self.tableView.indexPathForSelectedRow()
let row = myIndexPath?.row
detailViewController.webSite = webAddresses[row!]
所以我不知道该怎么做才是如何根据表视图控制器选择pdf文件。我想我需要创建一个变量......但我不确定。谢谢你的建议。
答案 0 :(得分:0)
以下是您的简单示例:
<强> TableViewController.swift 强>
import UIKit
class TableViewController: UITableViewController {
//Your PDF list
var pdfAddresses = [
"TestPDF",
"TestPDF2",
"TestPDF3",
"TestPDF4"]
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return pdfAddresses.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! UITableViewCell
// Configure the cell...
cell.textLabel?.text = pdfAddresses[indexPath.row] //Display PDF list in tableView
return cell
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "ShowAttractionDetails" {
let detailViewController = segue.destinationViewController as! AttractionDetailViewController
let myIndexPath = self.tableView.indexPathForSelectedRow()
let row = myIndexPath?.row
//Pass selected cell title to next View
detailViewController.webSite = pdfAddresses[row!]
}
}
}
<强> AttractionDetailViewController.swift 强>
import UIKit
class AttractionDetailViewController: UIViewController {
//Outlet of webView but you can create it programatically too.
@IBOutlet weak var webView: UIWebView!
//This will hold data which is passed from first View
var webSite : String?
override func viewDidLoad() {
super.viewDidLoad()
//Load selected PDF into webView.
if let webSite = webSite {
println(webSite)
if let pdf = NSBundle.mainBundle().URLForResource(webSite, withExtension: "pdf", subdirectory: nil, localization: nil) {
let req = NSURLRequest(URL: pdf)
webView.loadRequest(req)
}
}
}
}
查看此SAMPLE项目了解更多信息。