Introduction:
I have a class, which inherits from UIButton. In this class I want to update properties, like titleEdgeInsets, imageEdgeInsets, contentHorizontalAlignment.
My first approach was to use layoutSubviews:
override func layoutSubviews() {
super.layoutSubviews()
// update properties
}
The layoutSubviews creates an infinity loop, so that I've searched for an alternative method.
My Question:
Is it a common way, to use the willMove method for updating UIButton properties?
override func willMove(toWindow newWindow: UIWindow?) {
super.willMove(toWindow: newWindow)
// update properties
}
If not, why?
My goal is to align the imageView of the button left (with padding) and center the text.
UPDATE:
I need the button frame.size and the bounds.width to calculate the position of the text and the image view
All the properties you mentioned above can be set in the
initof theUIButtonthere is absolutely no need to set them inlayoutSubviewsorwillMove(toWindow.layoutSubviewswill be called multiple times so setting these properties again n agin in here makes no sense.willMove(toWindowwill be called when button is added to some view and button is loaded but you dont have to wait till then to set these properties. Because you already have a subclass of button, so I would suggest doingBy the way creating a subclass of
UIButtonis not recommended, so if you wanna simply assign these properties to your button you can rather have a extension toUIButtonEDIT:
Is this what you want??
No matter what the text is, text is always in centre and image is to its left with 10 pixel padding
EDIT 2:
As OP has confirmed that, he wants the button to be styled as showed in images above, posting the code to achieve the same
Hope it helps