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