ios - UIButton - alloc initWithFrame : vs. buttonWithType:

标签 ios objective-c uibutton

给定(任意):

CGRect frame = CGRectMake(0.0f, 0.0f, 100.0f, 30.0f);

下面两个代码片段有什么区别?

1.

    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = frame;

2.

    UIButton *button = [[[UIButton alloc] initWithFrame:frame] autorelease];

最佳答案

我认为它们是等价的。哈哈!诡计多端的问题,你这个鬼鬼祟祟的小混混!

推理

  1. -buttonWithType: 返回一个自动释放的 UIButton 对象。

  2. +[NSObject alloc] 默认标量实例变量为 0,所以 buttonType 应该是 0,或 UIButtonTypeCustom

优缺点

  1. 您可能会争辩说,使用 -buttonWithType: 并显式设置 buttonType 会更清晰,并且如果 Apple 更改 UIButtonTypeCustom 会更安全> 为 1 而不是 0(这肯定永远不会发生)。

  2. 另一方面,您也可以争辩说使用 -initWithFrame 足够清晰和安全。此外,许多 Xcode 示例项目(例如“TheElements”和“BubbleLevel”)都使用这种方法。一个优点是您可以在应用程序主线程的运行循环耗尽其自动释放池之前显式释放 UIButton。而且,这就是为什么我更喜欢选项 2。

关于ios - UIButton - alloc initWithFrame : vs. buttonWithType:,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6245882/

相关文章:

ios - 商标 "TM"字符如何显示或转换(非标准)\U0099?

ios - UIButton 子类标题更改

ios - 应用提交 : Invalid Binary - Invalid Signature

iphone - 如何检查 UITextfield 是否输入了数据?

ios - iOS 中的钥匙串(keychain)访问 : "Keychain failed to store the value with code: -50"

ios - 自动布局在设置 preferredMaxLayoutWidth 时在 UILabel iPhone 6/6+ 的顶部和底部添加额外的填充

ios - CoreData和MagicalRecord-仅在应用用户点击时,我应该如何正确处理更新数据?

ios - MPMediaPlayer indexOfNowPlayingItem 给出当前索引 9223372036854775807

ios - 添加目标 :action:forControlEvents: unrecognized selector sent to instance - uibutton in uitablecell

objective-c - 动画 UIButton