【问题标题】:Center Storyboard Views in autolayout在自动布局中居中故事板视图
【发布时间】:2016-05-17 15:42:22
【问题描述】:

所以基本上,我有一个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 个 ish 像素,而一侧有 20 个另一个。我不知道为什么。

我在 storyboard 中设置它,然后用 cnt 拖动它,然后在 viewDidAppear 中更改视图的属性以覆盖 storyboard。

我也尝试过这样做:

  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

等等

【问题讨论】:

  • 为什么不在故事板中应用约束??
  • 我被要求尽可能以编程方式完成,并尽可能避免使用情节提要。
  • 请使用自动布局,否则您将一团糟。我不知道是您的项目要求不使用自动布局还是有人告诉过您。如果有人告诉我,我是从体验你所遵循的错误方向

标签: ios swift autolayout nslayoutconstraint


【解决方案1】:

在现代应用程序中,您永远不应该直接设置.frame。尤其是在 viewDidAppear 中,您的布局会在旋转和 Slide Over 或 Split View 多任务处理中发生变化,同时保持可见。

正确的做法是始终使用 Auto Layout,并且通常在 Interface Builder 中应用所有 Auto Layout 约束,在必要时按大小类进行自定义,并在那里进行预览。任何错误的规格都可以通过这种方式更容易地纠正。优秀教程可以在raywenderlich.com找到:

【讨论】:

  • 明白。事情是这样的,这只是一个 iPhone 应用程序 - 或多或少是一个以编程方式执行视图的练习,故事板只是一个原型。也许我们这样做是为了向我们展示如何努力或愚蠢或其他什么,方法是,我不确定。我只是想知道为什么文本字段没有进入我设置的框架。我是否错误地设置了框架?如果我将代码放在 viewDidLoad 中,那么故事板将覆盖代码,因此它在 viewDidAppear 中。但同样,我不是专家,真的只是一个新学生,只是对此感到好奇。
  • 您对框架的更改将被下一次自动布局传递覆盖,一旦任何视图使其内容或位置无效,就会发生这种情况。如果你真的想和框架对抗,你可以在 `viewDidLayoutSubviews()` 覆盖中进行可见的帧更改,或者完全关闭自动布局。
猜你喜欢
  • 1970-01-01
  • 2013-07-28
  • 2018-05-28
  • 1970-01-01
  • 1970-01-01
  • 2015-11-30
  • 1970-01-01
  • 1970-01-01
  • 2018-04-15
相关资源
最近更新 更多