简体   繁体   English

UIView框架自动重置

[英]UIView frame auto reset

I have this simple code, initializing an UILabel 我有这个简单的代码,初始化UILabel

At first print, frame width/height are correct, but at second, all values of frame are 0. 第一次打印时,帧的宽度/高度是正确的,但是第二步,帧的所有值都是0。

let messageBoxFrame = CGRect(x: 0, y: 0, width: 1024, height: BAND_HEIGHT)
print(messageBoxFrame)
let messageBox = UILabel(frame: messageBoxFrame)
messageBox.textAlignment = .center
messageBox.textColor = UIColor.white
messageBox.backgroundColor = UIColor.blue
messageBox.sizeToFit()
print(messageBox.frame)

messageBox.sizeToFit() this line of code is adjusting your UILabel frame messageBox.sizeToFit()这行代码正在调整您的UILabel框架

As per this sizeToFit() 按照这个sizeToFit()

Call this method when you want to resize the current view so that it uses the most appropriate amount of space. 当您想调整当前视图的大小以使其使用最合适的空间时,请调用此方法。 Specific UIKit views resize themselves according to their own internal needs. 特定的UIKit视图根据其内部需求调整其大小。 In some cases, if a view does not have a superview, it may size itself to the screen bounds. 在某些情况下,如果视图没有超级视图,则它可能会将自己的大小调整到屏幕边界。 Thus, if you want a given view to size itself to its parent view, you should add it to the parent view before calling this method. 因此,如果希望给定视图将自身调整为其父视图的大小,则应在调用此方法之前将其添加到父视图。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM