2016-05-17 23 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()'覆盖中修改可见的框架,或者完全关闭自动布局。 –

相关问题