2016-09-21 95 views
0

我在Playground中使用Xcode 8和Swift 3創建了以下代碼。根據我讀過的內容,似乎應該顯示一個子視圖,大小爲30 x 30點,位於包含UIView的中心。我也嘗試了各種其他類型的約束無濟於事。內部UIView只是不顯示。以編程方式創建UIView約束,但錨點未應用

這應該是使用@IBDesignable和@IBInspectable的自定義UIView子類的一部分。如果我手動設置子視圖的框架,他們工作得很好,但我想要有東西自動調整大小,如果需要的選項。我在這裏使用了可視化格式化語言,還看到了其他一些例子,儘管我還沒有和他們一起運氣,我想我更喜歡使用錨點。任何線索爲什麼這不起作用?

import UIKit 

// Define a simple UIView to put a subview in 
let outer = UIView(frame: CGRect(x: 0, y: 0, width: 320, height: 480)) 

// Add a little style to verify that properties are updating 
outer.layer.borderWidth = 2.0 
outer.layer.borderColor = UIColor.green.cgColor 

// Create a subview 
let inner = UIView(frame: CGRect.zero) 

// I believe this is needed to set constraints manually 
inner.translatesAutoresizingMaskIntoConstraints = false 

// Add the subview. This displays outer, and it's just a box with a border 
outer.addSubview(inner) 

// Add a color so I can see it 
inner.backgroundColor = UIColor.black 

// These constraints should be enough to define the position and size 
inner.heightAnchor.constraint(equalToConstant: 30.0).isActive = true 
inner.widthAnchor.constraint(equalToConstant: 30.0).isActive = true 
inner.centerYAnchor.constraint(equalTo: outer.centerYAnchor).isActive = true 
inner.centerXAnchor.constraint(equalTo: outer.centerXAnchor).isActive = true 

outer.setNeedsDisplay() // This doesn't seem to do anything, but I tried it 
inner.setNeedsDisplay() // Same here 

inner.frame // Shows as {x 0 y 0 w 0 h 0} 

// Show the UIView, which looks exactly the same as before. 
outer 

回答

1

更換兩個setNeedsDisplay()與

outer.layoutIfNeeded()

+0

完美要求。非常感謝! –

相關問題