LoginSignup
15
14

More than 5 years have passed since last update.

SwiftでViewなどを遅延生成する

Posted at

UIViewはオブジェクトのなかでも比較的重いため、メモリ節約のために遅延生成をすることがあります。
Objective-Cではこんな記述をしてました。こうすることで titleLabel に初めてアクセスがあったときにUILabelが生成され、すでに生成済みの場合は保持しているものを返すという処理になっています。


@interface ViewController

@property (nonatomic) UILabel *titleLabel;

@end


@implementation ViewController

- (UILabel *)titleLabel {
    if (_titleLabel) {
        return _titleLabel;
    }

    _titleLabel = [UILabel new];
    _titleLabel.text = @"タイトル";
    _titleLabel.textColor = [UIColor greenColor];
    _titleLabel.font = [UIFont boldSystemFontOfSize:14];
    return _titleLabel;
}

@end

これのSwift版を調べていて、こういう書き方に落ち着きました。
クロージャを作って即時実行しています。さらに lazy キーワードをつけることでアクセスがあったときにクロージャが実行されるようになります。

class ViewController {

    lazy var titleLabel: UILabel = {
        let label = UILabel()
        label.text = "タイトル"
        label.textColor = UIColor.greenColor()
        label.font = UIFont.boldSystemFontOfSize(14)
        return label
    }()

}
15
14
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
15
14