如何通过点击UIView来执行segue

bag*_*els 5 ios segue swift

我想知道是否可以将UIView属性连接到UIViewController.通过连接a UIView,我想转换到第二个视图控制器.我通过拖动和编码尝试了几次,但我只是假装.我正在寻找不需要像使用seague那样编程的方法.

有没有实现这个目标的东西?

谢谢

Amm*_*sch 8

故事板模式支持此功能(至少现在.)将Tap Gesture识别器拖到您要单击的视图上.然后将手势识别器连接到您要显示的视图,就像任何其他segue过渡一样.确保任何包含视图的"已启用用户交互".无需代码. Apple文档


Dav*_*eek 5

要通过点击来执行segue UIView,您需要添加一个手势识别器。在我的示例中,我SubclassUIView编程方式实例化并添加了一个:

viewDidLoad(){

    // here we instantiate an object of our subclass
    let customView = MyViewSubclass(frame: CGRect(x: 0, y: 0, width: 100, height: 100))
    // here we add it to our ViewController
    self.view.addSubview(customView)

    // here we instantiate an object of gesture recognizer
    let gestureRec = UITapGestureRecognizer(target: self, action:  #selector (self.someAction (_:)))
    // here we add it to our custom view
    customView.addGestureRecognizer(gestureRec)
}

func someAction(sender:UITapGestureRecognizer){     
   performSegueWithIdentifier("Whazzzzup", sender: self)
}

// Swift 3
func someAction(_ sender:UITapGestureRecognizer){  

   // this is the function that lets us perform the segue   
   performSegue(withIdentifier: "Whazzzup", sender: self)
}
Run Code Online (Sandbox Code Playgroud)

如果您没有SubclassUIView,则只需添加一个UIView...

let customView = UIView(frame: CGRect(x: 0, y: 0, width: 100, height: 100))
Run Code Online (Sandbox Code Playgroud)

当然,您当然也可以将UIViewOutlet并添加手势识别器。

let gestureRec = UITapGestureRecognizer(target: self, action:  #selector (self.someAction (_:)))
myView.addGestureRecognizer(gestureRec)
Run Code Online (Sandbox Code Playgroud)

要呈现一个ViewController 没有segue的实例,您需要实例化ViewController:

func someAction(_ sender:UITapGestureRecognizer){
    let controller = storyboard?.instantiateViewController(withIdentifier: "someViewController")
    self.present(controller!, animated: true, completion: nil)
    // swift 2
    // self.presentViewController(controller, animated: true, completion: nil)
}
Run Code Online (Sandbox Code Playgroud)

您需要withIdentifier在ViewController的Attribute Inspector中设置:

在此处输入图片说明

在此示例withIdentifier中将是:LandingVC

如果您使用a UINavigationController并想要a back Button,则将ViewController其推入Navigation堆栈:

self.navigationController?.pushViewController(controller!, animated: true)
Run Code Online (Sandbox Code Playgroud)