In iOS, can a UIButton be added by alloc and initW

2019-08-16 16:45发布

A button can be added by:

UIButton *myButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
myButton.frame = CGRectMake(100, 100, 160, 50);
[myButton setTitle:@"click me" forState:UIControlStateNormal];
[self.view addSubview:myButton];

but can we go with the initWithFrame method:

UIButton *myButton2 = [[UIButton alloc] initWithFrame:CGRectMake(100, 300, 160, 50)];
//myButton2.buttonType = UIButtonTypeRoundedRect;
myButton2.titleLabel.text = @"click me";
[self.view addSubview:myButton2];

but line 2 above is commented out because it causes an error for a "read only" property, and with that line commented out, still no button shows up at all... can a UIButton be added if using initWithFrame to begin with?

(update: I set a yellow background to see the view's area, and found that the label text of button 2 actually shows up as "click me" in white... but touching it has no visual effect... so I wonder how to change code sample 2 to make it work...)

1条回答
对你真心纯属浪费
2楼-- · 2019-08-16 17:28

Yes of course it can. I got into a little bit of a discussion as to that readonly buttonType property a while back. The general concensus is that there is neither a safe way, nor a good reason, for anyone to switch the type of a button. And besides, +buttonWithType returns an instance of UIButton just as well as +Alloc and -init do, so it isn't a problem.

查看更多
登录 后发表回答