Xcode 5 になって、InterfaceBuilder や Storyboard で Auto Layout を設定しやすくなったけど、 コードで Auto Layout 設定したいときが稀にある。 例えば自分の場合、継承して使いまわすことを前提に View や ViewController のベースクラスを作るときとか。
一度 Auto Layout の便利さを体感したら、もう Frame を設定してまわるなんてやってられなくなる。 かといって、Auto Layout をコードで記述するのもなかなか苦行。 RubyMotion の motion-layout みたいに、良い感じにラップしたライブラリがあれば、少しは楽になるのに。 そう思ったんで、Objective-C にポートしてみた。
使い方は次の通り。
@interface TNAViewController () @property (nonatomic) TNALayoutManager *layoutManager; @end @implementation TNAViewController - (void)viewDidLoad { [super viewDidLoad]; UIButton *button1 = [UIButton buttonWithType:UIButtonTypeSystem]; button1.backgroundColor = [UIColor blueColor]; [button1 setTitle:@"button1" forState:UIControlStateNormal]; [self.view addSubview:button1]; UIButton *button2 = [UIButton buttonWithType:UIButtonTypeSystem]; button2.backgroundColor = [UIColor yellowColor]; [button2 setTitle:@"button2" forState:UIControlStateNormal]; [self.view addSubview:button2]; self.layoutManager = [[TNALayoutManager alloc] init]; self.layoutManager.view = self.view; self.layoutManager.subviews = @{ @"button1": button1, @"button2": button2, }; [self.layoutManager vertical:@"|-15-[button1]-10-[button2(==button1)]-15-|"]; [self.layoutManager horizontal:@"|-10-[button1]-10-|"]; [self.layoutManager horizontal:@"|-10-[button2]-10-|"]; [self.layoutManager strain]; } @end
motion-layout とほとんど変わらない。 実際にシミュレーターで表示してみたのがこちら。
横にしても
ばっちり配置されてる。
Podspec を用意したので、Podfile に
pod "TNALayoutManager", git: "https://github.com/tnakamura/TNALayoutManager.git"
って書けば CocoaPods でインストールできる。 CocoaPods のおかげで、オレオレライブラリが簡単に再利用できて開発が捗るな。
2016/10/27 追記
iOS 9 から NSAutoLayoutAnchor を使えば簡単に Auto Layout をコードで書けるようになったので、 自作ライブラリは使わなくなった。
保守するつもりもないので公開停止。