2

According to this answer, I can use intrinsicContentSize to automatically calculate the width/height. That's what I did, but the result is 0, 0

class AutoSizeUIButton: UIButton{
    override func intrinsicContentSize() -> CGSize {
        return CGSizeMake(self.frame.size.width, self.titleLabel!.frame.size.height)
    }
}


networkButton.setTitle("something-here", forState: .Normal)
networkButton.titleLabel?.font = UIFont(name: "HelveticaNeue", size: 20.0)!
let networkSize = networkButton.intrinsicContentSize()
print("button size", networkSize.width, networkSize.height)  //prints 0.0, 0.0

Am I doing something wrong? Note: I don't want to use constraints. I just want to print the width/height.

Community
  • 1
  • 1
TIMEX
  • 259,804
  • 351
  • 777
  • 1,080
  • Try this code UIFont *font = [UIFont fontWithName:@"Helvetica" size:30]; NSDictionary *userAttributes = @{NSFontAttributeName: font, NSForegroundColorAttributeName: [UIColor blackColor]}; NSString *text = @"hello"; ... const CGSize textSize = [text sizeWithAttributes: userAttributes]; – Ahmad Ishfaq May 08 '16 at 20:59

2 Answers2

5

Try networkButton.sizeThatFits.

let networkSize = networkButton.sizeThatFits(CGSizeZero)
print("button size", networkSize.width, networkSize.height)  

(The parameter passed to sizeThatFits is often ignored and poorly documented. I'm not sure if CGSizeZero works everywhere - maybe you should pass an arbitrarily large size)

EricS
  • 9,650
  • 2
  • 38
  • 34
3

Try this:

networkButton.sizeToFit()

Now the size of Network Button fits it's text

Pranav Wadhwa
  • 7,666
  • 6
  • 39
  • 61