2016-05-01 62 views
1

我有一個VideoTableController類,它擁有一堆YouTube視頻的桌面視圖。Swift如何讓webView加載更快

當選擇一個視頻時,它會啓動另一個視圖控制器,該視圖控制器中有一個網絡視圖,用於播放指定的YouTube視頻。

我試着把代碼加載到videoTableController的prepareForSegue函數中,但事情是VideoPlayer控制器還沒有被實例化,所以我不能修改video_view的值:UIWebView prepareForSegue函數。

我想知道如果我做了這個videoPlayer()在prepareForSegue函數中實例化它,然後修改值VideoPlayer.video_view.loadHTMLString()將工作或當videoPlayer被segued將其實例化的另一個實例?

這是我目前在我的錄像機類:

var video_player_url = "" 

class VideoPlayer: UIViewController { 

@IBOutlet weak var video_view: UIWebView! 

override func viewDidLoad() { 
    self.video_view.loadHTMLString("<iframe width=\"\(video_view.frame.width)\" height=\"\(video_view.frame.height)\" src=\"https://www.youtube.com/embed/\(video_player_url)\" frameborder=\"0\" allowfullscreen></iframe>", baseURL: nil) 
    super.viewDidLoad() 
    // Do any additional setup after loading the view. 
} 

這裏是我videoTableController類調用:

override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { 
    self.performSegueWithIdentifier("video_player_segue", sender: self) 
} 

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { 
    let indexPath = self.tableView.indexPathForSelectedRow 

    video_player_url = video_urls[indexPath!.row] 
    } 

回答

2

在prepareForSegue,類已經被實例化,但是它可能尚未從StoryBoard加載。這是它能夠在prepareForSegue中爲您提供目標控制器的方式。常用的技術是在類中設置其他變量,然後在目標控制器的viewWillAppear中,使用該值來執行您想要執行的任何操作。

class VideoPlayer : ViewController { 
    var video_player_url: String? 
    @IBOutlet weak var video_view: UIWebView! 

    override func viewWillAppear(animated: Bool) { 
     if let url = self.video_player_url { 
      self.video_view.loadHTMLString("<iframe width=\"\(video_view.frame.width)\" height=\"\(video_view.frame.height)\" src=\"https://www.youtube.com/embed/\(video_player_url)\" frameborder=\"0\" allowfullscreen></iframe>", baseURL: nil) 
     } 

    } 

} 

而在你的表視圖控制器...

class VideoTableController : UITableViewController { 
    // stuff goes here 

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { 
    let indexPath = self.tableView.indexPathForSelectedRow 
    // verify that indexPath is not nil or your app will crash. 
    let destinationController = segue.destinationViewController as! VideoPlayer 
    destinationController.video_player_url = video_urls[indexPath!.row] 
} 
+0

,完美的工作謝謝! –