在iOS中,是否可以通过alloc和initWithFrame添加UIButton? [英] In iOS, can a UIButton be added by alloc and initWithFrame?

查看:127
本文介绍了在iOS中,是否可以通过alloc和initWithFrame添加UIButton?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可以通过以下方式添加按钮:

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];

但是我们可以使用 initWithFrame 方法吗:

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];

但上面的第2行已被注释掉,因为它会导致只读属性出错,并且注释掉该行,仍然根本没有按钮...如果使用 initWithFrame 开头可以添加UIButton吗?

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?

更新:我设置了黄色背景以查看视图区域,发现按钮2的标签文本实际上显示为单击我为白色...但是触摸它没有视觉效果...所以我想知道如何更改代码示例2使其起作用...)

(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...)

推荐答案

是的,当然可以。不久前,我就该readonly buttonType属性进行了一些讨论。普遍的共识是,任何人都没有安全的方法,也没有充分的理由来切换按钮的类型。此外, + buttonWithType 返回UIButton的实例以及 + Alloc - init 做,所以这不是问题。

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.

这篇关于在iOS中,是否可以通过alloc和initWithFrame添加UIButton?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆