ios - 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.
解决方案
将视图放在 UIViewController 中,调用一个函数,在控制器的 viewDidLayoutSubviews() 中调整视图的大小
override func viewDidLayoutSubviews() {
myView.resize()
}
推荐阅读
- javascript - Visual Studio Code 不允许我调试我编写的特定代码
- c# - 带有 Blazor 的 ASP.NET Core:无法确定 cookie 身份验证
- java - JSP 抛出空指针异常
- php - 如何在 PHP 中运行 websocket 服务器时运行计算?
- php - 有没有办法在 php/Laravel 中不提示下载文件
- css - 如何使元素前后的倾斜结尾?
- php - 配置 Codeigniter-3.1.10 以使用 mongodb
- max - SSRS(报表生成器)来自同一数据集的最小值和最大值
- php - 警告:在第 234 行遇到一个非数字值
- php - MyISAM 比赛条件 / LOCK TABLES