我以编程方式检索一堆ViewControllers。这些ViewController的源代码在我的StoryBoard中,我使用
创建它们let page = storyboard?.instantiateViewController(withIdentifier: "features_view_controller")
我想要做的是,以编程方式访问我在StoryBtroller中的ViewController中的UILabel。这样的事可能吗?
var label = page!.view("identifer")
我该怎么做?
答案 0 :(得分:1)
您应该将@IBOutlet属性添加到UIViewController类。
class YourViewController: UIViewController {
@IBOutlet weak var label: UILabel! // link it with UILabel in the storyborad.
}
然后您就可以访问UILabel:
if let page = UIStoryboard().instantiateViewController(withIdentifier: "features_view_controller") as? YourViewController {
page.label //your label, which is currently nil, because the view controller still does not draw view.
}
但是如果您需要更新(例如标签文本),那么您应该准备“数据传输对象”并将其传递给视图控制器。视图加载后,您可以更新UILabel。示例如下:
class YourViewController: UIViewController {
@IBOutlet weak var label: UILabel!
var text: String? //text for label.
override func viewDidLoad() {
super.viewDidLoad()
label.text = text
}
}
if let page = UIStoryboard().instantiateViewController(withIdentifier: "features_view_controller") as? YourViewController {
page.text = "Test"
//show page (present or push view controller) or manually send command for drawing view (page.view)
}
答案 1 :(得分:0)
您可以为子视图提供标记,并将其标记为: - YourController.view.viewWithTag(yoursubviewtag)