ios - 自动布局中的中心 Storyboard View

标签 ios swift autolayout nslayoutconstraint

基本上,我有一个 UITextView,我希望它位于我的 UIView 的中心。下面是我的 View Controller 代码:

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)        
    }    
}

我将背景 View 的不透明度更改为 50%,并将 textView 的背景颜色更改为蓝色,但是当我运行它时,蓝色背景很好地位于 UIView 内,例如一侧有 10 个像素,另一侧有 20 个像素另一个。我不确定为什么。

我在 storyboard 中设置它,cnt 拖动它,然后在 viewDidAppear 中更改 View 的属性以覆盖 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)
}

然后收到一个奇怪的错误,说布局约束有问题。

单独设置view的高宽和起点会不会更简单?如果是这样,我怎样才能做这样的伪代码:

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

等等

最佳答案

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

正确的做法是始终使用自动布局,并且通常在 Interface Builder 中应用所有自动布局约束,在必要时按尺寸类别进行自定义,并在那里预览它们。这样可以更容易地纠正任何错误的规范。优秀教程可见raywenderlich.com :

关于ios - 自动布局中的中心 Storyboard View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37280781/

相关文章:

ios - Facebook API - 如何取消图形请求

ios - SLComposeViewController 共享文本出现空白的问题 ios9

ios - 为什么设置 UIButton 的字体会扰乱我的图层

ios - 如何在 iOS 中裁剪进入圆圈内的图像

ios - 在 Bitbucket 存储库上推送具有多个项目的工作区

ios - 单元格中的 CGAffineTransform 动画不起作用

ios - Facebook登录后触发segue

ios - TableView HeaderSections 隐藏按钮

ios - 如何将 UICollectionView 项目的大小调整为具有 Collection View 高度的正方形大小?

swift - 没有设置高度限制有关系吗?