Search code examples
iosswiftuibuttonuikit

Swift iOS: UIButton.frame gives all 0s


I am new to iOS and Swift and the UIKit so there are many items that have proven confusing. I create a UIButton, add some text, and then TRY to get the button's CGRect, but all the values are zero. I am actually just interested in the width.

Here is my code (menuButtonMaxWidth is a class var)

    menuButtonMaxWidth = 0
    let overflowItem1 = UIButton()
    let checkboxCharacter: Character = "\u{25EF}"
    overflowItem1.setTitle("\(checkboxCharacter) Allow Hub Wifi Reset", for: [])
    overflowItem1.setTitleColor(UIColor.white, for: [])
    overflowItem1.addTarget(self, action: #selector(overflowItem1Clicked(_:)), for: UIControl.Event.touchUpInside)
    overflowItem1.translatesAutoresizingMaskIntoConstraints = false
    if overflowItem1.frame.width > menuButtonMaxWidth {
        menuButtonMaxWidth = overflowItem1.frame.width
    }

The overflowItem1.frame.width always gives zero! Debugging shows that the CGRect of overflowItem1.frame has all zero values. What am I doing wrong? This seems like it should be so straight forward. Thanks for any help. I must be missing something or doing something that is an iOS no-no but have not caught on yet.

I am using Xcode 12 and I assume the latest version of Swift.


Solution

  • Call sizeToFit() on your button to resize it for its content.

        let overflowItem1 = UIButton()
        let checkboxCharacter: Character = "\u{25EF}"
        overflowItem1.setTitle("\(checkboxCharacter) Allow Hub Wifi Reset", for: [])
        overflowItem1.setTitleColor(UIColor.white, for: [])
                
        overflowItem1.sizeToFit()
        print(overflowItem1.frame.width)