提问人:Riddham paliwal 提问时间:12/25/2020 最后编辑:MaxVRiddham paliwal 更新时间:12/25/2020 访问量:66
IB网点即使在故事板中连接,也变得为零
IB outlets are getting nil even though they are connected in storyboard
问:
我是 Xcode 的新手,我创建了一个 UIPageViewController 和一个视图控制器,因为它是数据容器,这是我的代码:
class RootPageControllerViewController: UIPageViewController,UIPageViewControllerDataSource {
var myControllers:[UIViewController] = []
let pages:[String] = ["first","second","third","fourth","fifth","six","seven"]
let story = UIStoryboard(name: "Main", bundle: nil)
override func viewDidLoad() {
super.viewDidLoad()
for text in pages{
let vc = self.story.instantiateViewController(identifier: "dataContainer") as! DataContainer
vc.setText(text)
myControllers.append(vc)
}
configureController()
}
func configureController(){
self.dataSource = self
if let first = myControllers.first{
self.setViewControllers([first], direction: .forward, animated: true,completion: nil)
}
}
func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? {
guard let index = myControllers.firstIndex(of: viewController),index>0 else { return nil }
let before = index-1
return myControllers[before]
}
func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? {
guard let index = myControllers.firstIndex(of: viewController),index<(myControllers.count - 1) else {
return nil
}
let after = index + 1
return myControllers[after]
}
}
class DataContainer: UIViewController {
@IBOutlet var titleView: UILabel!
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
}
override func viewDidLoad() {
super.viewDidLoad()
}
func setText(_ mssg:String){
if titleView != nil{
titleView.text = mssg
}
else{
print("reference is null")
}
}
}
我的插座连接正确,我已经检查过很多次,但它们在运行时也变得为零......如何防止插座被取消引用
答:
0赞
DonMag
12/25/2020
#1
@IBOutlet
在加载视图之前,连接无效。
当您 时,您将获得对该控制器对象的引用,但视图尚未加载。.instantiateViewController
这是解决此问题的一种方法:
for text in pages{
let vc = self.story.instantiateViewController(identifier: "dataContainer") as! DataContainer
// add this line
vc.loadViewIfNeeded()
vc.setText(text)
myControllers.append(vc)
}
评论