2016-05-17 101 views
0

所以基本上,我有一個UITextView,我想集中在我的UIView。這裏是我下面的視圖控制器代碼:中心故事板在自動佈局中的看法

import UIKit 

class OpeningScreenViewController: UIViewController { 

    @IBOutlet weak var topBarUIView: UIView! 
    @IBOutlet weak var topViewTextView: UITextView! 

    override func viewDidAppear(animated: Bool) { 
     let superViewWidth = view.frame.size.width 
     let superViewHeight = view.frame.size.height 

    //creating the top bar 
     topBarUIView.frame = CGRect(x: 0, y: 0, width: superViewWidth, height: superViewHeight * 0.1) 
     topBarUIView.backgroundColor = UIColor.grayColor().colorWithAlphaComponent(0.5) 

    //adding text to the top bar 
     topViewTextView.frame = CGRectMake(0, 0, superViewWidth, superViewHeight * 0.1) 
     topViewTextView.backgroundColor = UIColor.blueColor() 
     topViewTextView.text = "Hello World" 
     topViewTextView.textAlignment = NSTextAlignment.Center 
     topViewTextView.font = UIFont(name: "Arial", size: 24)   
    }  
} 

我改變我的背景考慮到50%的不透明度和TextView的到的藍色背景色,但是當我運行此,藍色背景中的UIView好,像一邊是10個像素,另一邊是20個像素。我不知道爲什麼。

我在故事板中設置它,然後將它拖動到上面,然後更改viewDidAppear中視圖的屬性以覆蓋故事板。

我也試着做這樣的事情:

override func viewDidAppear(animated: Bool) {  
    // Get the superview's layout 
    let margins = view.layoutMarginsGuide 

    // Pin the leading edge of myView to the margin's leading edge 
    topBarUIView.leadingAnchor.constraintEqualToAnchor(margins.leadingAnchor).active = true 

    // Pin the trailing edge of myView to the margin's trailing edge 
    topBarUIView.trailingAnchor.constraintEqualToAnchor(margins.trailingAnchor).active = true 

    // Give myView a 1:2 aspect ratio 
    topBarUIView.heightAnchor.constraintEqualToAnchor(topBarUIView.widthAnchor, multiplier: 2.0) 
} 

,並得到一個奇怪的錯誤說,佈局約束都出現問題。

分別設置視圖的高度和寬度以及起點會更容易嗎?如果是的話我怎麼能這樣做僞代碼:

topBar.startingPoint = (x,y) 
topBar.height = this 
topBar.width = this 

+0

在stroryboard你爲什麼不申請限制? –

+0

我被要求儘可能以編程的方式來做,並儘可能地避免故事板。 – dnaland

+0

請使用自動佈局,否則它會讓你處理混亂。我不知道它的項目要求是不使用自動佈局還是有人告訴過你。如果有人告訴我比你告訴你從體驗到錯誤的方向,你以下是 –

回答

1

在現代的應用程序,你永遠不應該直接設置.frame。特別是不在viewDidAppear - 您的佈局會隨着旋轉以及幻燈片放映或分割視圖多任務處理而變化,同時保持可見狀態。

正確的做法是始終使用自動佈局,並且通常在Interface Builder中應用所有自動佈局約束,在必要時按大小類自定義,並在其中預覽它們。任何錯誤規範都可以通過這種方式更容易地糾正。優秀的教程可以在raywenderlich.com發現:

+0

瞭解。事情就是這樣,這只是一個iPhone應用程序 - 或多或少的以程序化方式將故事板視圖作爲原型進行練習。也許我們這樣做是爲了向我們展示有多麼困難或愚蠢或什麼,這個方法是,我不確定。我只是想知道爲什麼文本字段沒有進入我設置的框架。我錯誤地設置了框架嗎?如果我把代碼放在viewDidLoad中,那麼故事板就會覆蓋代碼,因此它在viewDidAppear中。但是,我不是專家,只是一個新生,只是對此感到好奇。 – dnaland

+0

您對幀的更改將被下一次自動佈局傳遞所覆蓋,一旦任何視圖使其內容或位置失效,就會發生這種情況。如果你真的想打架,你可以在'viewDidLayoutSubviews()'覆蓋中修改可見的框架,或者完全關閉自動佈局。 –

相關問題