Khorwin Khorwin - 11 days ago 6
Swift Question

UIView frame auto reseted

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)


Can anyone know this problem ?

Thanks,

Answer

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.