在FirstViewController中,我从JSON获取响应,并希望将获取的响应传递给另一个视图控制器.Below是我迄今为止用于解析和传递响应的代码。
FirstViewController
var fn:String! //globally declared variable
我试过在FirstViewController中解析的代码
do {
let detailsDictionary:NSDictionary = try JSONSerialization.jsonObject(with: data!, options:.allowFragments) as! Dictionary<String, AnyObject> as NSDictionary
print(detailsDictionary)
let details = detailsDictionary["Data"] as! [[String:AnyObject]]
print(details)
for dtl in details
{
self.fn = dtl["Father_Name"] as? String ?? "NA"
print(self.fn) //here i'm getting the exact value from JSON
}
}
}
SecondViewController
在SecondViewController中有一个名为profile_name的Label,并希望将该解析后的字符串( fn )设置为Label的文本。为此我宣布另一个变量为全局变量。
var pname:String!
下面是我用来从FirstViewController获取值的代码。
viewDidLoad()
{
let othervc = FirstViewController()
self.pname = othervc.fn
self.profile_name.text = self.pname
}
问题:我尽了最大的努力来获得所需的输出,但我得到了无响应。
请帮助。
答案 0 :(得分:0)
在第二个ViewController中
let strName:String!
在First ViewController中
let strOne = "This is for testing"
let objstory = self.storyboard?.instantiateViewController(withIdentifier: "yout Secoond ViewController Storybord ID") as! YourSecondViewControllerName
objstory.strNam = strOne
self.navigationController?.pushViewController(objstory, animated: true)
答案 1 :(得分:0)
您的更新代码无效。
let othervc = FirstViewController()
创建FirstViewController
的新实例(不是获得JSON的实例)。
你应该像这样处理它:
在FirstViewController
let fn = dtl["Father_Name"] as? String ?? "NA"
let svc = SecondViewController() // Or maybe instantiate from Storyboard, or maybe you already have a reference to it
svc.pname = fn
present(svc, animated: true, completion: nil)
然后在SecondViewController
override func viewDidLoad() {
super.viewDidLoad()
profile_name.text = pname
}
我建议您抽出时间重新阅读Apple's View Controller programming guide。
原始答案
你遇到的问题......
vcvalue.profile_name.text = fn
profile_name
是nil
,因为此时尚未加载视图控制器的视图。
您应该通过在LeftSideMenuViewController
var name: String?
然后设置
vcvalue.name = fn
然后在LeftSideMenuViewController
override func viewDidLoad() {
super.viewDidLoad()
profile_name.text = name
}
另外,一些基本提示......
@IBOutlet
s private
- 这会阻止您像现在一样意外地分配给他们viewWill/DidDis/Appear
方法,则必须在某个时候致电super
。switch/case
所以这......
let a = indexPath.row
switch(a)
{
case 0 :
if(a == 0)
{
return 45
}
break
etc
可能就是......
switch indexPath.row {
case 0...4:
return 45
case 5:
return 50
default:
break
}