[英]scrollView is nil when called from viewdidload
我要在單擊navigationItem時滾動視圖。 但是..這里有一些錯誤。
我想像滾動視圖一樣。 它工作正常,但是...當我從viewdidload函數中調用scrollView時,scrollView為零!
我已經做出了喜歡滑動視圖的感覺。 但是我想在單擊導航項(心臟標記)時進行滑動查看。
我的ViewController viewdidload函數-工作正常
@IBOutlet weak var scrollView: UIScrollView!
var V1 : LeftViewController = LeftViewController(nibName: "LeftViewController", bundle: nil)
var V2 : CenterViewController = CenterViewController(nibName: "CenterViewController", bundle: nil)
var V3 : RightViewController = RightViewController(nibName: "RightViewController", bundle: nil)
override func viewDidLoad() {
super.viewDidLoad()
self.addChildViewController(V1)
self.scrollView.addSubview(V1.view)
V1.didMoveToParentViewController(self)
self.addChildViewController(V2)
self.scrollView.addSubview(V2.view)
V2.didMoveToParentViewController(self)
self.addChildViewController(V3)
self.scrollView.addSubview(V3.view)
V3.didMoveToParentViewController(self)
var V2Frame : CGRect = V2.view.frame
V2Frame.origin.x = self.view.frame.width
V2.view.frame = V2Frame
var V3Frame : CGRect = V3.view.frame
V3Frame.origin.x = 2 * self.view.frame.width
V3.view.frame = V3Frame
println(self)
println(scrollView)
println(V2.view.frame)
self.scrollView.setContentOffset(CGPointMake(V2Frame.origin.x, self.view.frame.size.height), animated: false)
self.scrollView.contentSize = CGSizeMake(self.view.frame.width * 3, self.view.frame.size.height) }
我的ViewController clickEvent函數-為什么scrollView為nil?
func clickEvent() {
self.scrollView?.scrollRectToVisible(V2.view.frame, animated: true)
println(self)
println(scrollView)
println(V2.view.frame)
//self.scrollView.setContentOffset(CGPointMake(V2.view.frame.origin.x, self.view.frame.size.height), animated: true)
}
我從其他CenterViewController在Viewcontroller中調用clickEvent-它可以調用,但是...在ViewController中,clickEvent函數的scrollView為nil。如何解決此問題?
func clickEvent(sender: AnyObject) {
ViewController().clickEvent()
}
在您的代碼中,您可以在viewDidLoad
設置一個視圖框架。 在viewDidLoad
視圖僅加載到內存中,而尚未在屏幕中加載,因此,如果嘗試在viewDidLoad
向視圖詢問其框架,則不會得到一個consolidante值。而是使用viewWillAppear
來向其詢問框架,然后得到正確的值,因為視圖已准備好顯示。
該類本身不包含布局信息。 因此,視圖控制器對象無法知道哪個視圖對象連接到了哪個IBOutlet。 視圖控制器必須通過情節提要板本身進行實例化。 您可以使用以下方法
storyboard?.instantiateInitialViewController()
storyboard?.instantiateViewControllerWithIdentifier("YOUR_VC_STORYBOARD_ID")
使用第二種方法時,請不要忘記設置情節提要標識符。 當您轉到View Controller-> Identity Inspector-> Storyboard_ID時,可以找到輸入標識符的位置
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.