2015-09-27 16 views
0

的最小數量我在我的ViewController下面的代碼對準stackview以編程不使用硬編碼的CGRect和約束

let imageView    = UIImageView() 
imageView.backgroundColor = UIColor.blueColor() 
imageView.heightAnchor.constraintEqualToConstant(120.0).active = true 
imageView.widthAnchor.constraintEqualToConstant(120.0).active = true 
imageView.image = UIImage(named: "buttonFollowCheckGreen") 

let textLabel    = UILabel() 
textLabel.widthAnchor.constraintEqualToConstant(self.view.frame.width).active = true 
textLabel.heightAnchor.constraintEqualToConstant(20.0).active = true 
textLabel.text = "Hi World" 
textLabel.font = UIFont(name:kFontName, size:24) 
textLabel.textAlignment = .Center 

let stackView = UIStackView() 
stackView.axis = UILayoutConstraintAxis.Vertical 
// stackView.distribution = UIStackViewDistribution.EqualSpacing 
// stackView.alignment = UIStackViewAlignment.Center 
stackView.spacing = 16.0 

stackView.addArrangedSubview(imageView) 
stackView.addArrangedSubview(textLabel) 
stackView.translatesAutoresizingMaskIntoConstraints = false; 

self.view.addSubview(stackView) 

stackView.centerXAnchor.constraintEqualToAnchor(self.view.centerXAnchor).active = true 
stackView.centerYAnchor.constraintEqualToAnchor(self.view.centerYAnchor).active = true 

然而,這種呈現如下屏幕的頂部: actual

我想有它呈現如下:

expected

上述代碼的最小更改是如何實現的。我希望stackview上的一個屬性可以將它對齊到頂部。

+0

代碼中的最後兩行將您的視圖中的堆棧視圖居中。你可以先改變它。 – Abizern

+0

即使我註釋掉您提到的兩行(即原始問題中也編輯過),我也得到了相同的結果 – Das

+0

您用什麼約束替換它們? – Abizern

回答

1

將最後兩行:

stackView.centerXAnchor.constraintEqualToAnchor(self.view.centerXAnchor).active = true 

let constraint = NSLayoutConstraint(
    item: stackView, 
    attribute: .Top, 
    relatedBy: .Equal, 
    toItem: topLayoutGuide, 
    attribute: .Bottom, 
    multiplier: 1.0, 
    constant: 0.0 
) 
view.addConstraint(constraint) 

而且,你是在代碼中創建視圖,您使用的是帶有自動佈局,所以你需要通過添加以下兩行

關閉自動尺寸面具
imageView.translatesAutoresizingMaskIntoConstraints = false 
textLabel.translatesAutoresizingMaskIntoConstraints = false 

你仍然在你的堆棧視圖中與視圖有衝突,但這不是問題的一部分,所以我會留下讓你嘗試修復。

+0

感謝您的幫助@Abizern。這很好! – Das