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);
  }];

效果如下图所示:

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);
}];

效果如下图所示:

iOS Simulator Screen Shot 2014年11月23日 上午1.54.31.png
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 发现 关注 消息 iOS 第三方库、插件、知名博客总结 作者大灰狼的小绵羊哥哥关注 2017.06.26 09:4...
    肇东周阅读 12,259评论 4 61
  • 喜欢吃面包 软欧是最爱 闲来无事 自己做软欧 惬意极了
    棉兜妈咪阅读 273评论 0 0
  • 某君,我学生,在家乡深山任教二十余年,被调到城里任官,却厌烦城市的繁华嘈杂,欲请辞回山中王峰乡任教。如今人心...
    老海李亚强阅读 369评论 2 4
  • Question: You are playing the following Nim Game with you...
    W有来有去阅读 172评论 0 0
  • 人行道上无法选择的红绿灯时间,中学课程里无法选择的科目内容,围棋中无法选择的棋子颜色。每件事有它的规则,你出生那天...
    夏不绿阅读 1,083评论 5 18