如何通过xib创建自定义UIView并在xib中使用

如何通过xib创建自定义UIView并在xib中使用,第1张

Xib和Storyboard的使用我就不多叙述。关于如何用Xib自定义一个UIView,并将其添加在ViewController上,使用AutoLayout添加约束条件,使其跟随控制器ViewController的约束条件变化而变化呢?请看下文。

1、 创建一个继承UIView的子类TestView和xib文件

这里写图片描述

2、 选中xib中的File’s Owner,设置右边工具栏中的Custom Class为你所创建的文件TesView

3、 在TestView.h中添加一个IBOutlet属性

@property (nonatomic, weak) IBOutlet UIView *view

1

1

4、 将此IBOutlet 连接到TestView.xib 的View

这里写图片描述

5、在TestView.m文件中初始化,如下:

- (instancetype)initWithCoder:(NSCoder *)aDecoder

{

self = [super initWithCoder:aDecoder]

if (self) {

NSString *className = NSStringFromClass([self class])

self.view = [[[NSBundle mainBundle] loadNibNamed:className owner:self options:nil] firstObject]

[self addSubview:self.view]

return self

}

return nil

}

1

2

3

4

5

6

7

8

9

10

11

12

1

2

3

4

5

6

7

8

9

10

11

12

或者在awakeFromNib中添加也可以:

- (void)awakeFromNib {

[[[NSBundle mainBundle] loadNibNamed:NSStringFromClass([self class]) owner:self options:nil] firstObject]

[self addSubview:self.view]

}

1

2

3

4

1

2

3

4

6、在Storyboard中引用xib文件

这里写图片描述

下面是详细的步骤

(1)新建一个空的(Empty)xib文件,File->New,在面板中选择User Interface->Empty,如下图所示:

将文件命名为CustomTableViewCell,表示自定义的cell意思。

(2)拖动一个TableViewCell到空的(Empty)xib文件中,如下图,

(3)修改CustomTableViewCell的高度为90,通过属性面板来设置,如下图,

(4)拖一个UIIMageView到CustomTableViewCell的xib文件,设置该UIImageView控件的tag值为10;再拖两个UILabel到xib文件,设置tag分别为1和2,其布局方式如下图,

上面的几个步骤就进行了CustomTableViewCell的自定义,下面的步骤就是使用这个通过xib文件进行自定义的cell。

(5)选中CustomTableViewCell,点击左上角的File's Owner,如下图

选中这个xib文件中的File's Owner是为了设置CustomTableViewCell的文件所有者,接着看下一步。

(6)在右侧的面板,选择“Show the Identify Inpector”选项,如下图

这时候我们发现CustomTableViewCell的File's Owner为NSObject,因为我要在我的RootViewController中使用,所以我将"NSObject"替换为"RootViewController",表明这个cell的所有者是RootViewController。(PS:你需要将此处的NSObject改为你使用该CustomTableViewCell的ViewController文件名。)

(7)在使用该CustomTableViewCell的ViewController的头文件中写下如下代码,

@interface RootViewController:UIViewController

{

}

@property (nonatomic, strong) IBOutlet UITableViewCell *customCell

@end

(8)在CustomTableViewCell.xib文件中,拖动File's Owner指向TableViewCell,如下图

(9)在d出的界面中选择customCell选项,如下图

这就是为什么第(7)步骤要在RootViewController.h文件中声明一个IBOutlet关键字修饰的customCell变量的原因了。

(10)新建一个数据模型文件Person,继承自NSObject,其代码如下,

//Person.h文件

@interface Person : NSObject

@property (nonatomic, strong) NSString *name

@property (nonatomic, strong) NSString *headStr

@property (nonatomic, strong) NSString *speechText

@end

//Person.m文件

#import "Person.h"

@implementation Person

@end

之所以叫它模型文件,是因为该文件中的属性与CustomTableViewCell上面的控件所需的内容一致,以MVC的视角来看Person就是M(Model),CustomTableViewCell就是V(View),而RootViewController就是C(Controller)。

(11)在RootViewController中初始化TableView数据源_persons

(12)在-tableView:cellForRowAtIndexPath:中使用CustomTableViewCell.xib创建cell

以上就是具体的步骤。


欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/bake/11757686.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2023-05-18
下一篇2023-05-18

发表评论

登录后才能评论

评论列表(0条)

    保存