Khorwin Khorwin - 2 months ago 44
Swift Question

UIView frame auto reseted

I have this simple code, initializing an


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)
let messageBox = UILabel(frame: messageBoxFrame)
messageBox.textAlignment = .center
messageBox.textColor = UIColor.white
messageBox.backgroundColor =

Can anyone know this problem ?



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.