这两个按钮显示相同的ViewController。
ViewController1.swift
@objc func btnEdit()
{
print("Edit")
let editDeptt = self.storyboard?.instantiateViewController(withIdentifier: "Add Department") as! AddDepartmentVC
self.navigationController?.pushViewController(editDeptt, animated: true)
}
@IBAction func btnNewDeptt(_ sender: Any)
{
let addDepttVC = self.storyboard?.instantiateViewController(withIdentifier: "Add Department") as! AddDepartmentVC
self.navigationController?.pushViewController(addDepttVC, animated: true)
}
ViewController2.swift
override func viewDidLoad() {
super.viewDidLoad()
//How to identify i come from which button
}
答案 0 :(得分:2)
在名为AddApartmentVC
的{{1}}中添加一个属性,并在推送视图控制器之前进行设置。
首先创建一个枚举:
action
然后在enum Action {
case edit, newDept, unknown
}
:
AddApartmentVC
然后在你的按钮'操作,将属性设置为所需的值:
var action = Action.unknown
或
editDeptt.action = .edit
最后,在addDepttVC.action = .newDept
中,检查值:
viewDidLoad()
答案 1 :(得分:0)
在identify
中添加一个实例变量名称AddDepartmentVC
,然后从当前的VC中设置相同的值,就像这样
let editDeptt = self.storyboard?.instantiateViewController(withIdentifier: "Add Department") as! AddDepartmentVC
editDeptt.identify = "button1"
然后你可以推送它并检查AddDepartmentVC
答案 2 :(得分:0)
在ViewController2
。swift中,声明一个像这样的变量
class ViewController2: UIViewController{
let var originTag: Int = 0
}
override func viewDidLoad() {
super.viewDidLoad()
if originTag == 0
{
// come from button 1 - btnEdit
}
else
{
// come from button 2 - btnNewDeptt
}
}
在ViewController 1
中,像这样设置originTag
。
@objc func btnEdit()
{
print("Edit")
let editDeptt = self.storyboard?.instantiateViewController(withIdentifier: "Add Department") as! AddDepartmentVC
editDeptt.originTag = 0
self.navigationController?.pushViewController(editDeptt, animated: true)
}
@IBAction func btnNewDeptt(_ sender: Any)
{
let addDepttVC = self.storyboard?.instantiateViewController(withIdentifier: "Add Department") as! AddDepartmentVC
addDepttVC.originTag = 1
self.navigationController?.pushViewController(addDepttVC, animated: true)
}
答案 3 :(得分:0)
只需为按钮指定标签 -
Button1.tag=1
Button2.tag=2
然后检查你的按钮 -
func onClickButton(sender: UIButton){
switch(sender.tag){
case 101 :
print("I am from button 1")
default :
print("I am from button 2")
}
}
答案 4 :(得分:0)
使用它完全适合你。
在Viewcontroller1.Swift
中获取上面类的一个公共变量public var btnComingFrom = "first"
@objc func btnEdit()
{
btnComingFrom = "first"
print("Edit")
let editDeptt =
self.storyboard?.instantiateViewController(withIdentifier: "Add Department")
as! AddDepartmentVC
self.navigationController?.pushViewController(editDeptt, animated: true)
}
@IBAction func btnNewDeptt(_ sender: Any)
{
btnComingFrom = "second"
let addDepttVC = self.storyboard?.instantiateViewController(withIdentifier: "Add Department") as! AddDepartmentVC
self.navigationController?.pushViewController(addDepttVC, animated: true)
}
ViewController2.swift
override func viewDidLoad()
{
super.viewDidLoad()
if btnComingFrom == "first"
{
print("you are coming from first button")
}
if btnComingFrom == "second"
{
print("you are coming from second button")
}
}