【问题标题】:How to write computed initializers in Objective C?如何在 Objective C 中编写计算初始值设定项?
【发布时间】:2017-04-24 09:54:11
【问题描述】:

今天我在长时间使用objective c时想到了一个问题。假设我有以下用 swift 3.0 编写的计算初始化程序代码。

private let loginButton: UIButton = {
        let button = UIButton(type: .system)
        button.backgroundColor = UIColor(hex: 0x0083C5, alpha: 1)
        button.setTitle("Login", for: .normal)
        button.setTitleColor(UIColor.white, for: .normal)
        button.titleLabel?.font = UIFont.systemFont(ofSize: 20, weight: .bold)
        button.layer.cornerRadius = 5
        return button
    }() 

上面的代码返回一个 UIButton 的实例。如何在目标 C 中编写相同的代码?

更新:我已经知道使用延迟实例化的方式了。有没有其他方法可以创建不可变实例?

【问题讨论】:

标签: ios objective-c swift


【解决方案1】:

我用这样的东西

@interface TestClass : NSObject
@property (nonatomic, readonly) UIButton* button;
@end

@implementation TestClass
@synthesize button=_button;
-(UIButton*)button
{
  if (_button==nil) {
    _button = [UIButton buttonWithType:UIButtonTypeSystem];
    ...
  }
  return _button;
}

@end

【讨论】:

  • 感谢您的发帖
猜你喜欢
  • 2018-02-12
  • 2011-03-31
  • 2012-01-14
  • 1970-01-01
  • 2020-07-20
  • 1970-01-01
  • 1970-01-01
  • 2012-12-24
  • 2020-01-13
相关资源
最近更新 更多