无法获取UIVew大小

时间:2018-06-30 20:29:44

标签: ios swift uiview constraints

我在代码中动态添加了UIViews。我要添加很多视图。例如:

let typeImage = UIImageView()
typeImage.translatesAutoresizingMaskIntoConstraints = false
rootView.addSubview(typeImage)
typeImage.widthAnchor.constraint(equalToConstant: 28).isActive = true
typeImage.heightAnchor.constraint(equalToConstant: 28).isActive = true
typeImage.leftAnchor.constraint(equalTo: rootView.leftAnchor, constant: 4).isActive = true
typeImage.topAnchor.constraint(equalTo: rootView.topAnchor, constant: 4).isActive = true
typeImage.backgroundColor = gh.myRed
typeImage.image = UIImage(named: "ic_question_bej")

我想计算所有添加元素的总和,最后将此计数值设置为我的根视图高度。问题是

typeImage.frame.size.height
typeImage.bounds.size.height

总是返回0.0

那么如何通过代码在新添加的UIView的CGFloat中获取高度? 也许我应该设置rootview的高度,以另一种方式包装所有子视图?

修改

Xcode加载视图会有一些延迟,如果您尝试在将视图添加到父级后立即尝试获取视图大小,则会得到0.0个大小。

您必须在che大小之前致电yourCustomView.layoutIfNeeded()

感谢Chenjtc的正确答案。

2 个答案:

答案 0 :(得分:1)

如果您想要CGFloat中多个视图高度的总和,可以这样:

Do
DoEvents
On Error Resume Next
Set frm = IE.Document.getElementByID("exportButton")
On Error GoTo 0
Loop While frm Is Nothing

或者如果您想设置新的UIView高度,可以通过更改来实现:

let viewHeight = self.view.frame.height  //this in CGFloat
let sumHeight = viewHeight + ... other UIViews
print(sumHeight) // 568.0 for iPhone SE

//

收件人:

typeImage.heightAnchor.constraint(equalToConstant: 28).isActive = true

答案 1 :(得分:1)

您可以添加如下代码: typeImage.layoutIfNeeded() 在代码之前:
typeImage.frame.size.height typeImage.bounds.size.height 约束不会立即布局,您应该使用layoutIfNeeded来布局视图,然后可以获取框架