0

I'm trying to get the real height of my custom UIButton. But I always get a value that is way smaller than I expected. I get something around 30 but expected something about 45.

override func awakeFromNib() {
  print(self.frame.height)
  self.layer.cornerRadius = self.layout.frame.height / 2.0
  self.clipsToBounds = true
  self.titleLabel?.adjustsFontSizeToFitWidth = true
}

This is my code, but at runtime somehow autolayout changes the size, which is perfect, but I can not set the right cornerRadius (always too small). So maybe I need the multiplier or something like that. I already testet with adding the contentEdgeInsets of top and bottom, but it made no difference.

Thanks Tobias

Peter Hornsby
  • 4,208
  • 1
  • 25
  • 44
Tobias
  • 578
  • 1
  • 5
  • 23

2 Answers2

5

The view hasn't been laid out in awakeFromNib(). Set your corner radius when layout has guaranteed to have happened.

For a view:

override func layoutSubviews() {
  super.layoutSubviews()
  layer.cornerRadius = frame.height / 2.0
}

For a UIViewController:

override func viewDidLayoutSubviews() {
  super.viewDidLayoutSubviews()
  view.layer.cornerRadius = view.frame.height / 2.0
}
0

Try calling self.layoutIfNeeded() before you print the size

juanjo
  • 3,737
  • 3
  • 39
  • 44