2017-08-20 243 views
0

我有ViewController,並且裏面有UIView。從UIView執行segue

這UIView的具有單獨的類MyView的,有很多UI元素 - 其中之一是的CollectionView。

我要的是當選擇MyView的收集要素之一來執行SEGUE。但是,當我嘗試

performSegue(withIdentifier: "myIdintifier", sender: self) 

添加行收集的觀點didSelectItemAt方法,我得到錯誤

使用未解決的標識符「performSegue」

而且據我所知,這是因爲我在擴展UIView而不是UIViewController的類內部做到這一點。

那麼在這種情況下,我該如何執行?而且我該如何準備繼續?

+0

,您可以使用自定義委託來觸發UIViewController中的事件,然後你可以使用performSegue –

+0

請你提供更詳細的例子作爲一個答案? – moonvader

回答

1

這裏我將逐步評估它。

步驟 - 1

使用協議創建自定義委託如下片段會指導你的自定義的UIView。 必須存在於您的自定義視圖範圍之外。

protocol CellTapped: class { 
    /// Method 
    func cellGotTapped(indexOfCell: Int) 
} 

不要忘了你的自定義視圖

var delegate: CellTapped! 

去與你的集合視圖didSelect方法創建如下上述類的委託變量如下

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { 
     if(delegate != nil) { 
      self.delegate.cellGotTapped(indexOfCell: indexPath.item) 
     } 
    } 

步驟 - 2

讓我們走到了你的VIE w控制器。將CellTapped提供給您的視圖控制器。

class ViewController: UIViewController,CellTapped { 

    @IBOutlet weak var myView: MyUIView! //Here is your custom view outlet 
    override func viewDidLoad() { 
     super.viewDidLoad() 
     myView.delegate = self //Assign delegate to self 
    } 

    // Here you will get the event while you tapped the cell. inside it you can perform your performSegue method. 
    func cellGotTapped(indexOfCell: Int) { 
     print("Tapped cell is \(indexOfCell)") 
    } 
} 

希望這會幫助你。

+0

謝謝!真棒:) – moonvader

1

您可以使用協議/代表來實現。

// At your CustomView 

protocol CustomViewProtocol { 
    // protocol definition goes here 
    func didClickBtn() 
} 


var delegate:CustomViewProtocol 




@IBAction func buttonClick(sender: UIButton) { 
    delegate.didClickBtn() 
    } 




//At your target Controller 
public class YourViewController: UIViewController,CustomViewProtocol 

let customView = CustomView() 
customView.delegate = self 

func didClickSubmit() { 
    // Perform your segue here 
} 
+0

非常感謝! – moonvader