在viewDidLoad和viewDidAppear之间传递数据

时间:2017-03-27 08:32:57

标签: ios swift swift3

我想知道如果在ViewDidLoad中有条件地创建并且未初始化,我如何在viewDidLoad和viewDidAppear之间传递值。

override func viewDidLoad() {
    if let foo = self.foo {
        let webView = UIWebView(frame: self.view.frame)
        scrollView.addSubView(webView)
    }
}

override func viewDidAppear() {
    // How do I use my conditionally created webView here?
    func doSomething(webView: UIWebView) {
        // Do stuff
    }
}

5 个答案:

答案 0 :(得分:4)

两个方法都在同一个范围内 - 它们在同一个类实例中,你可以使用一个实例变量,例如:

fileprivate var webView: UIWebView?

override func viewDidLoad() {
    super.viewDidLoad()

    if let foo = self.foo {
        let webView = UIWebView(frame: self.view.frame)
        scrollView.addSubView(webView)

        self.webView = webView
    }
}

override func viewDidAppear() {
    super.viewDidAppear()

    if let webView = self.webView {
       // do something with my webView
    }
}

答案 1 :(得分:1)

只需将webView移至班级范围,您就可以在班级的任何地方访问

class MyClass : UIViewController
{

    var webView : UIWebView?

    override func viewDidLoad() {
        if let foo = self.foo {
            webView = UIWebView(frame: self.view.frame)
            scrollView.addSubView(webView)
        }
        else
        {
            webView = nil // or set to some default
        }
    }

    override func viewDidAppear() {
        // How do I use my conditionally created webView here?
        if webView != nil
        {
            // Do stuff
        }
    }
}

答案 2 :(得分:1)

您可以将webView设置为全局变量:

_client.Search<Project>(...); // Response.Hits should be a list of IHit<Projects>

一种类似的更好方法:

_client.Search<SomeResponseType>(searchDescriptor => searchDescriptor
    .Type("project")
    .Query(q => q.Term("name", "fooBar")));

答案 3 :(得分:1)

试试这个,

    class ViewController
    {
         //Init glabal variable
         let webView:UIWebView? = nil

          override func viewDidLoad() 
          {
             if let foo = self.foo {
               webView = UIWebView(frame: self.view.frame)
               scrollView.addSubView(webView)
          }

          override func viewDidAppear() 
          {
              if(webView != nil)
              {
                  func doSomething(webView: UIWebView) 
                  {
                     // Do stuff
                   }
              }
         }
   }

答案 4 :(得分:0)

您可以将webView用作全局变量

let webView : UIWebview {
    return UIWebView(frame: self.view.frame)
}

override func viewDidLoad() {
    if let foo = self.foo {
        scrollView.addSubView(webView)
    }
}
override func viewDidAppear() {
    doSomething()
}

func doSomething() {
    // Do stuff
}

或者您可以访问scrollview子视图

for subview in scrollView.subviews {
    if subview is UIWebview {
        doSomething(webview: subview as! UIWebView)
    }
}