如何使用Masonry第三方库,来约束纯代码中的控件

来源:互联网 发布:优惠券采集源码 编辑:程序博客网 时间:2024/06/05 00:32

大概学习IOS课程快4个月了,然后最近才开始接触第三方库。就自己来整理下Masonry的使用


这是下载好的Masonry 里面的文件,我们暂时只用到其中的Masonry。

 

在项目中选择Add Files to xxxx 来导入Masonry 这个库,然后在ViewController中包含一下

#import "ViewController.h"#import "Masonry.h"

因为是纯代码 ,所以要把根视图加载到Window 上 具体代码如下

在AppDelegate.h 中声明

@property (strong, nonatomic) UIWindow *window;@property (strong, nonatomic) ViewController *rootView;

在.m中是

@implementation AppDelegate@synthesize rootView;- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {    // Override point for customization after application launch.    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen]bounds]];    self.window.backgroundColor = [UIColor whiteColor];    self.rootView = [[ViewController alloc]init];    [self.window setRootViewController:self.rootView];    [self.window makeKeyAndVisible];    return YES;}

然后是一个小demo 练习,应用Masonry对控件的约束

//添加一个背景图片    self.bgView =[[UIImageView alloc]init];    self.bgView.image =[UIImage imageNamed:@"loginbg.png"];    [self.view addSubview:self.bgView];    [self.bgView mas_makeConstraints:^(MASConstraintMaker *make) {            //通过top和left 确认self.bgView 的左上角原点        make.top.equalTo(self.view.mas_top);        make.left.equalTo(self.view.mas_left);                    //通过CGSizeMake 确认self.bgView 的长宽数据        make.size.mas_equalTo(CGSizeMake(self.view.frame.size.width, self.view.frame.size.height));            }];
 

再加一个按钮和一个LOGO 图片

//关闭按钮    self.backBtn = [[UIButton alloc]init];    [self.backBtn setBackgroundImage:[UIImage imageNamed:@"closebt.png"] forState:UIControlStateNormal];        // [self.backBtn addTarget:self action:@selector() forControlEvents:UIControlEventTouchUpInside];    [self.view addSubview:self.backBtn];    [self.backBtn mas_makeConstraints:^(MASConstraintMaker *make) {        make.top.equalTo(self.view.mas_top).with.offset(30);        make.left.equalTo(self.view.mas_left).with.offset(10);        make.size.mas_equalTo(CGSizeMake(21, 21));    }];        //logo 图片    self.logolmg = [[UIImageView alloc]init];    self.logolmg.image = [UIImage imageNamed:@"LOGO.png"];    [self.view addSubview:self.logolmg];    [self.logolmg mas_makeConstraints:^(MASConstraintMaker *make) {            //通过top和centerx确认self.logolmg的中心点        make.top.equalTo(self.view.mas_top).with.offset(105);                make.centerX.mas_equalTo(self.view.mas_centerX);                make.size.mas_equalTo(CGSizeMake(104, 104));    }];

还有的就不都展示了 最后的效果是


有了纯代码 都快忘了故事板 



0 0
原创粉丝点击