如何通过点击UIView来执行segue

时间:2016-10-18 20:27:07

标签: ios swift segue

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

有没有达到这个目标的东西?

由于

2 个答案:

答案 0 :(得分:8)

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

答案 1 :(得分:5)

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

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)
}

如果您没有Subclass UIView,那么您只需添加UIView ...

let customView = UIView(frame: CGRect(x: 0, y: 0, width: 100, height: 100))

此外,你当然可以带上你的UIView插座并添加手势识别器。

let gestureRec = UITapGestureRecognizer(target: self, action:  #selector (self.someAction (_:)))
myView.addGestureRecognizer(gestureRec)

要显示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)
}

您需要在ViewController的属性检查器中设置withIdentifier

enter image description here

在此示例中,withIdentifier将为:LandingVC

如果您正在使用UINavigationController并想要back Button,请按导航堆栈上的ViewController

self.navigationController?.pushViewController(controller!, animated: true)