我在一个类Main_Screen中有一个IBOutlet,它可以连接到一个主ViewController,它有一个ScrollView,但是如果我尝试得到它则返回nil
视图控制器中的代码
import UIKit
class ViewController: UIViewController , UIScrollViewDelegate {
@IBOutlet weak var scrollVieww: UIScrollView!
override func viewDidLoad() {
super.viewDidLoad()
self.scrollVieww.pagingEnabled = true
self.scrollVieww.delegate = self
let storyboard = UIStoryboard(name: "Main", bundle: nil)
if let vc = storyboard.instantiateViewControllerWithIdentifier("MainScreen") as? Main_Screen {
// imageview returns nil :(
let imageView = vc.avatarImageView
}
// Do any additional setup after loading the view, typically from a nib.
let V1 = self.storyboard?.instantiateViewControllerWithIdentifier("HomeScreen") as UIViewController!
//Add initialized view to main view and its scroll view and also set bounds
self.addChildViewController(V1)
self.scrollVieww.addSubview(V1.view)
V1.didMoveToParentViewController(self)
V1.view.frame = scrollVieww.bounds
//Initialize using Unique ID for the View
let V2 = self.storyboard?.instantiateViewControllerWithIdentifier("MainScreen") as UIViewController!
//Add initialized view to main view and its scroll view also set bounds
self.addChildViewController(V2)
self.scrollVieww.addSubview(V2.view)
V2.didMoveToParentViewController(self)
V2.view.frame = scrollVieww.bounds
//Create frame for the view and define its urigin point with respect to View 1
var V2Frame: CGRect = V2.view.frame
V2Frame.origin.x = self.view.frame.width
V2.view.frame = V2Frame
//The width is set here as we are dealing with Horizontal Scroll
//The Width is x3 as there are 3 sub views in all
self.scrollVieww.contentSize = CGSizeMake((self.view.frame.width) * 2, (self.view.frame.height))
}
答案 0 :(得分:4)
简短的回答:不要这样做。您应该将另一个视图控制器的视图视为私有。
如果您需要操纵另一个视图控制器的UI,请添加用于请求更改UI的公共方法,然后让VC中的代码进行更改。
这是更好的设计,它避免了其他视图控制器的视图尚未被创建的情况,所以它们没有,并且它失败/崩溃与#34 ;在试图打开可选的"时遇到nil;消息。