2

I have a scenario where I need to change UIEdgeInsets for UIButton which is added to the UITableViewCell, I set it in layoutSubviews but that's called a number of times, it also work's with init too but I am not sure that's really a place because that will called only once.

override func layoutSubviews() {
        super.layoutSubviews()
        if imageView != nil {
            titleEdgeInsets = UIEdgeInsets(top: 52, left: -10, bottom: 0, right:-10)
        }
    }

Can someone tell me which one is the ideal place and why?

Retro
  • 3,985
  • 2
  • 17
  • 41

2 Answers2

1

awakeFromNib will be called when a new cell is loaded from a xib or storyboard , but not when a cell is re-used. But during awakeFromNib the frame layouts do not appear . UIEdgeInsets will not effected by frame so i prefer to call it at awakeFromNib not in layoutSubviews

layoutSubviews you will get correct frame so used only with stylish that need correct frame like corner radius

Abdelahad Darwish
  • 5,969
  • 1
  • 17
  • 35
  • So you mean UIEdgeInsets never changes even if the super and self-view frame changes as this button only show when needed and have title below the image? My concern this because most of the people suggest to setup this in layoutSubview like here https://stackoverflow.com/questions/4201959/label-under-image-in-uibutton, my button is subclass and added programmatically. – Retro May 07 '18 at 07:39
  • UIEdgeInsets not effected by Button frame it just inset from frame what ever this frame is – Abdelahad Darwish May 07 '18 at 07:42
0

Use awakeFromNib() if you use xib.

It call one time and this from documentation to awakeFromNib():

Typically, you implement awakeFromNib for objects that require additional set up that cannot be done at design time. For example, you might use this method to customize the default configuration of any controls to match user preferences or the values in other controls. You might also use it to restore individual controls to some previous state of your application.

Or if you don't use xib just use init because it called once.

Ivan Smetanin
  • 1,999
  • 2
  • 21
  • 28