2017-08-20 132 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