简体   繁体   中英

UIView frame auto reset

I have this simple code, initializing an UILabel

At first print, frame width/height are correct, but at second, all values of frame are 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

As per this 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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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