进入IT行业多年,也算一个老猿了,今天分享一下xib使用方式,希望可以帮助新人学习。
我们从头开始新建一个UIView,然后给它绑定xib文件,然后在这个view上添加一个UILabel并添加约束。下面我们开始。

首先点File进入创建文件界面

然后选择empty点击Next

在弹出的页面Save As:后面的输入框输入xib的名称,这里我们起名TextView,注意这里起的名字要和xib相关联的UIView的名字保持一致,输入完名字点击Create

创建完成后会发现目录里面多了一个TestView.xib文件

先选中TextView.xib文件,点击右上角加号,弹出的页面左上角有个搜索框,输入UIView,在搜索列表找到View控件,将其拖到xib正中间区域

将View的Class改成TextView,至此xib文件和TextView关联成功了

先拖入一个UILabel

再让label居中,这里涉及到xib的屏幕适配和约束问题,我们不做详细讨论,就事论事,只讨论水平和垂直问题。
先选中Label,再点击底部菜单栏两个长方形的小图标,然后勾选水平居中选项Horizontally in Container和垂直居中选项Vertically in Container,最后点击Add 2 Constraintsts添加约束

我们在ViewController.m中引入头文件TextView.h,然后在viewdidload里面初始化这个view并让它在页面显示。下面贴出ViewController.m中代码
#import "ViewController.h"
#import "TestView.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
TestView *view = [[[NSBundle mainBundle]loadNibNamed:@"TestView" owner:nil options:nil]lastObject];
view.frame = CGRectMake(0, 0,[UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height);
[self.view addSubview:view];
}
@end
至此运行Xcode,模拟器上出现下面的页面就说明自定义xib成功显示了。

网友评论