首页 > 解决方案 > UIView - What override will allow updating a UIView frame

问题描述

I have a UIView .xib, and am subclassing UIView. When I load the Nib, the frame of the view is set and awakeFromNib() is called.

I have 3 buttons. When I load the view, I pass in callbacks for each button. If one or more of the callbacks is nil, then I hide the buttons and resize the view:

let viewSize = 50
var adjustedSize = 0
if (self.option2String == nil){
    self.option2View.isHidden = true
    adjustedSize -= viewSize
}
if (self.option3String == nil){
    self.option3View.isHidden = true
    adjustedSize -= viewSize
}
let _size = self.innerView.frame.size
let size = CGSize(width: _size.width, height: _size.height + CGFloat(adjustedSize))
self.innerView.frame = CGRect(origin: self.innerView.frame.origin, size: size)

I have tried putting this code in awakeFromNib(), and didMoveToSuperview(), but the frame does not change size.

If I enclose the last line in DispatchQueue.main.async, then it works. But I'm concerned that this is just luck due to timing.

Is this best practice? Where can I resize a view from within a UIView subclass?

EDIT: Confirmed, the DispatchQueue.main.async is just luck. It only works 50% of the time.

标签: iosswiftuiview

解决方案


将视图放在 UIViewController 中,调用一个函数,在控制器的 viewDidLayoutSubviews() 中调整视图的大小

override func viewDidLayoutSubviews() {
   myView.resize()
}

推荐阅读