iOS initWithFrame:frame] 与 [UIButton buttonWithType] 对比
来源:互联网 发布:c语言产生0 9的随机数 编辑:程序博客网 时间:2024/05/01 12:18
What's the difference between the following two code snippets?
1.
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom]; button.frame = frame;
2.
UIButton *button = [[[UIButton alloc] initWithFrame:frame] autorelease];
I think they're equivalent. Haha! Trick question you sneaky little punk!
Reasoning
-buttonWithType:
returns an autoreleasedUIButton
object.
+[NSObject alloc]
defaults scalar instance variables to0
, sobuttonType
should be0
, orUIButtonTypeCustom
.Pros & Cons
You could argue that it's clearer to use
-buttonWithType:
and setbuttonType
explicitly and that it's safer in case Apple changesUIButtonTypeCustom
to be1
instead of0
(which will most certainly never happen).On the other hand, you could also argue that it's clear & safe enough to use
-initWithFrame
. Plus, many of the Xcode sample projects, such as "TheElements" & "BubbleLevel," use this approach. One advantage is that you can explicitly release theUIButton
before the run loop for your application's main thread has drained its autorelease pool. And, that's why I prefer option 2.I would strongly suggest using the first approach (
+buttonWithType
), because that's the only way to specify the button type.If you
+alloc
and-initWithFrame:
, thebuttonType
is set to some standard value (not sure which, and this could change in later versions of the SDK) and you can't change the type afterwards because thebuttonType
property is read only.
- iOS initWithFrame:frame] 与 [UIButton buttonWithType] 对比
- 用UIButton的类方法ButtonWithType创建时调用的是initWithFrame方法
- frame与iframe对比
- IOS bounds与Frame
- iOS Frame与Bound
- ios视图frame和bounds的对比
- ios视图frame和bounds的对比
- ios视图frame和bounds的对比
- ios学习--initWithFrame方法
- ios中的initWithFrame
- ios 关于 initWithFrame 方法
- IOS之initWithFrame
- IOS系列-initWithFrame
- iOS UIButton setTitle与setAttributedTitle
- initWithCoder与initWithFrame
- initWithFrame 与initWithCoder
- UIButton 设置 imageView frame
- iOS initWithCoder, initWithFrame那些事儿
- [C++11]_[初级]_[shared_ptr的使用场景]
- CodeForces 626 A. Robot Sequence(水~)
- C/C++基础::sizeof() 与 sizeof(string)
- 文件合成器
- LeetCode 30 - Substring with Concatenation of All Words
- iOS initWithFrame:frame] 与 [UIButton buttonWithType] 对比
- 第三方框架
- 空悲切
- Android 三种跨界面的通讯方式
- css滚动条样式制定 jscrollpane
- android中用户头像设置的一点心得——关于bitmap被回收的问题
- (八)利用processing实现类似吃豆人的运行效果
- js javascript:void(0) 真正含义
- 高质量PHP代码的50个实用技巧:非常值得收藏