【发布时间】: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