2016-12-05 38 views
2

我有一個帶標題的UICollectionView。我在這個標題按鈕中添加了 ,然後我爲這個UICollectionReusableView類型的標頭創建了一個類。然後我試圖一個動作添加到該按鈕,在類類型UICollectionReusableView標題中的按鈕用於推送新的視圖控制器

,但是,當我寫這行我有錯誤

@IBAction func goToMovie(_ sender: AnyObject) { 
     let st = self.storyboard?.instantiateViewController(withIdentifier: "aaa") as! aaa 
     self.navigationController?.pushViewController(st, animated: true) 

    } 

錯誤信息:value of type 'className' has no member 'storyboard'

我怎麼能去通過此按鈕查看其他視圖?

回答

2

您得到的錯誤是因爲UICollectionReusableView沒有storyboard屬性。它也沒有navigationController屬性。

您需要執行該轉換,而不是在可重用視圖中,而是從包含它的viewController中執行。爲了做到這一點,你需要一個自定義委託或一個回調塊,以告訴視圖控制器頭部已被點擊並觸發推送。

要使用的塊/閉合/回調:

在可重複使用的視圖中添加的完成閉合:

var completion: (() -> Void)?

接着,在您的goToMovie FUNC刪除這些兩行,並添加然後請致電:

completion?()

然後在你申報你的頭觸發這樣的過渡視圖控制器:在

protocol HeaderDelegate { 
    func headerTapped(sender: UICollectionReusableView) 
} 

然後:

. . . 
headerView.completion = { 
    let storyboard = UIStoryboard(name: "WhateverYourSBNameIs", bundle: nil) 
    let aaaVC = storyboard.instantiateViewController(withIdentifier: "WhateverYourIdentifierIs") as! AAAViewController 
    self.navigationController?.pushViewController(st, animated: true) 
} 

要使用自定義委託

創建協議header添加代表屬性

var delegate: HeaderDelegate? 

然後當你聲明的標題:

. . . 
header.delegate = self 
. . . 

然後使視圖控制器符合委託:

extension ViewController: HeaderDelegate { 

    func headerTapped(sender: UITableViewCell) { 
     let storyboard = UIStoryboard(name: "WhateverYourSBNameIs", bundle: nil) 
     let aaaVC = storyboard.instantiateViewController(withIdentifier: "WhateverYourIdentifierIs") as! AAAViewController 
     self.navigationController?.pushViewController(st, animated: true) 

    } 
} 

如果視圖控制器不需要知道哪個頭被竊聽,你可以從委託函數中刪除sender: UITableViewCell參數。

希望這會有所幫助。我會親自使用封閉FWIW。

+0

我應該在這裏寫下'var completion:(() - > Void)? – amjad

+0

和這些行'headerView.completion = { }讓故事板。 。 。等我放在哪裏? – amjad

+0

'var completion:(() - > Void)?'應該放在頭文件的任何位置。當你聲明頭裏面'func collectionView(_ collectionView:UICollectionView,viewForSupplementaryElementOfKind kind:String,在indexPath:IndexPath) - > UICollectionReusableView' – PJayRushton

相關問題