Not Story 指南

苹果官方的文档建议使用 Storyboard ,这个指南则描述了如何在代码中写布局和导航逻辑,抛开孰优孰略的争论,作为一种风格并采用。

不使用 Storyboard

新建一个 SingeleViewApplication , 然后在 plist 中删除 storyboard 的设置,在文件中删除 Main.Storyboard , 删除 ViewController 。

在 Appdelegate.m 的 application:didFinishLaunchingWithOptions: ,设置 RootController

self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
self.window.rootViewController = [[HomeViewController alloc] initWithLayout:[[HomeLayout alloc] init]];
[self.window makeKeyAndVisible];

使用布局对象

按照 MVC 的逻辑,将界面分为两层: ViewController 和 Layout , 各自的接口:

ViewController:

@interface ViewController : UIViewController

@property(nonatomic, strong) id layout;

- (id)initWithLayout:(id)layout;

@end

Layout:

@interface Layout : NSObject

@property(nonatomic, strong) UIView *rootView;;

- (void)layout:(UIView *)rootView;

@end

在 HomeLayout 中这样控制界面布局:

- (void)layout:(UIView *)rootView {
  [super layout:rootView];
  [self.rootView setBackgroundColor:[UIColor whiteColor]];
}

使用Masonry

Masonry是一个简化AutoLayout的约束的语法的库,详见Masonry@Github

使用 �TopLayoutGuide 和 BottomLayoutGuide

现在让我们尝试在顶部放置一个搜索框

  self.searchBar = [[UISearchBar alloc] init];
  [self.rootView addSubview:self.searchBar];
  [self.searchBar mas_makeConstraints:^(MASConstraintMaker *make){
    make.top.equalTo(self.rootView.mas_top);
    make.width.equalTo(self.rootView.mas_width);
  }];

效果如下图所示:

Not Story 指南_第1张图片
iOS Simulator Screen Shot 2014年11月23日 上午1.44.37.png

为了纠正这个问题,我们需要使用TopLayoutGuide, �先修改Layout的接口:

@interface Layout : NSObject

@property(nonatomic, strong) UIView *rootView;
@property(nonatomic, strong) UIView *topLayoutGuide;
@property(nonatomic, strong) UIView *bottomLayoutGuide;

- (void)layout:(UIView *)rootView topLayoutGuide:(UIView *)topLayoutGuide bottomLayoutGuide:(UIView *)bottomLayoutGuide;

@end

我们就可以在布局代码中指定ViewController的TopLayoutGuide:

self.searchBar = [[UISearchBar alloc] init];
[self.rootView addSubview:self.searchBar];
[self.searchBar mas_makeConstraints:^(MASConstraintMaker *make){
  make.top.equalTo(self.topLayoutGuide.mas_bottom);
  make.width.equalTo(self.rootView.mas_width);
}];

效果如下图所示:

Not Story 指南_第2张图片
iOS Simulator Screen Shot 2014年11月23日 上午1.54.31.png

你可能感兴趣的:(Not Story 指南)