如何在使用alloc后初始化UIButton的类型?

tan*_*boy 1 iphone objective-c uibutton ios

我知道我们可以使用该buttonWithType方法获取具有特定类型的UIButton.

UIButton * button = [UIButton buttonWithType:(UIButtonTypeRoundedRect)];
Run Code Online (Sandbox Code Playgroud)

今天,我随便使用UIButton的alloc/init方法创建一个UIButton:

UIButton * button = [[UIButton alloc] initWithFrame:CGRectMake(20, 300, 100, 50)];
Run Code Online (Sandbox Code Playgroud)

然后我发现没有办法改变按钮的类型.因为UIButton的buttonType属性是readonly.

在UIKit.framework中,UIButton.h:

@property(nonatomic,readonly) UIButtonType buttonType;
Run Code Online (Sandbox Code Playgroud)

我的问题是:如果我使用alloc/init创建一个UIButton,我可以更改UIButton的类型吗?如果没有,因为UIButton中没有任何init方法-initWithType,我们只能使用该+buttonWithType方法来获取自动释放UIButton.听起来有点奇怪,为什么不提供initWithType方法呢?

Cod*_*aFi 5

为什么甚至必须分配和init if + buttonWithType为你处理?只需改变你的想法:

UIButton * button = [UIButton buttonWithType:(UIButtonTypeRoundedRect)];
[button setFrame:CGRectMake(20, 300, 100, 50)];
Run Code Online (Sandbox Code Playgroud)