How to initialize a subclass UIButton correctly ?

https://developer.apple.com/documentation/uikit/uibutton/1624028-buttonwithtype?language=objc

Discussion

This method is a convenience constructor for creating button objects with specific configurations. If you subclass UIButton, this method does not return an instance of your subclass. If you want to create an instance of a specific subclass, you must alloc/init the button directly.

My test:

@interface MyButton : UIButton
@end

@implementation MyButton
@end

test output:

NSLog(@"%@", NSStringFromClass([MyButton buttonWithType:UIButtonTypeCustom].class));

output:

MyButton

the document is old or wrong ?

Answered by Frameworks Engineer in 714833022

The documentation is wrong. Calling [MyButton buttonWithType:UIButtonTypeCustom] is expected to return an instance of MyButton.

The statement in discussion is not very clear.

It means you cannot declare this initialiser in the subclass init. This fails:

    init() {
        super.init(type: UIButtonType.roundedRect)
    }

.

The meaning is much clearer here (that's Swift, but it's similar):

https://stackoverflow.com/questions/50442513/subclass-of-uibutton-cant-call-the-buttontype-initializer

Accepted Answer

The documentation is wrong. Calling [MyButton buttonWithType:UIButtonTypeCustom] is expected to return an instance of MyButton.

How to initialize a subclass UIButton correctly ?
 
 
Q