首页 > 其他 > 详细

使用纯代码进行界面布局

时间:2015-12-17 12:26:32      阅读:289      评论:0      收藏:0      [点我收藏+]

1 问题

纯代码布局就是重写布局方法viewDidLayoutSubviews,在该方法内部计算每个子视图的frame属性。本案例将学习如何使用纯代码进行布局,使界面上的Button和Label控件始终保持在固定的位置,如图1、图2所示:

技术分享 

技术分享

2 方案

首先创建一个SingleViewApplication项目,将自动布局功能关闭。

在Stroyboard的场景中拖放两个Button控件和一个Label控件,Button放置在屏幕的上方,并且大小一样,Label控件放置在屏幕的右下角。

然后在ViewController类中重写布局方法viewDidLayoutSubviews,在该方法中根据父视图的bounds计算Button和Label的frame。

3 步骤

实现此案例需要按照如下步骤进行。

步骤一:创建项目,添加控件

首先创建一个SingleViewApplication项目,在右边栏的检查器一中将自动布局功能关闭,如图3所示:

技术分享

在Stroyboard的场景中拖放两个Button控件和一个Label控件,Button放置在屏幕的上方,并且大小一样,Label控件放置在屏幕的右下角,如图4所示:

技术分享

步骤二:重写布局方法viewDidLayoutSubviews,进行界面布局

将Storyboard中的Button控件和Label控件关联成ViewController的私有属性,代码如下所示:

@interface ViewController : UIViewController

@property (weak, nonatomic) IBOutlet UIButton *button1;

@property (weak, nonatomic) IBOutlet UIButton *button2;

@property (weak, nonatomic) IBOutlet UILabel *label;

@end

在ViewController类中重写布局方法viewDidLayoutSubviews,在该方法中根据父视图的bounds计算Button和Label的frame,代码如下所示:

- (void)viewDidLayoutSubviews

{

    [super viewDidLayoutSubviews];

    CGFloat buttonWidth = (self.view.bounds.size.width - 20 - 20 - 10) * 0.5;

    CGRect frame = CGRectMake(20, self.button1.frame.origin.y, buttonWidth, 40);

    self.button1.frame = frame;

    

    frame = CGRectMake(self.button1.frame.size.width+30, self.button2.frame.origin.y, buttonWidth, 40);

    self.button2.frame = frame;

    

    frame = self.label.frame;

    self.label.frame = CGRectMake(self.view.bounds.size.width-20-frame.size.width, self.view.bounds.size.height-20-frame.size.height, frame.size.width, frame.size.height);

}

4 完整代码

本案例中,ViewController.m文件中的完整代码如下所示:

#import "ViewController.h"

@interface ViewController ()

@property (weak, nonatomic) IBOutlet UIButton *button1;

@property (weak, nonatomic) IBOutlet UIButton *button2;

@property (weak, nonatomic) IBOutlet UILabel *label;

@end

 

@implementation ViewController

- (void)viewDidLayoutSubviews

{

    [super viewDidLayoutSubviews];

    CGFloat buttonWidth = (self.view.bounds.size.width - 20 - 20 - 10) * 0.5;

    CGRect frame = CGRectMake(20, self.button1.frame.origin.y, buttonWidth, 40);

    self.button1.frame = frame;

    

    frame = CGRectMake(self.button1.frame.size.width+30, self.button2.frame.origin.y, buttonWidth, 40);

    self.button2.frame = frame;

    

    frame = self.label.frame;

    self.label.frame = CGRectMake(self.view.bounds.size.width-20-frame.size.width, self.view.bounds.size.height-20-frame.size.height, frame.size.width, frame.size.height);

}

@end

 

使用纯代码进行界面布局

原文:http://www.cnblogs.com/yhj1787354782/p/5053392.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!