在object-c编程中,有很多需要自定义的控件,或者视图。那么我们要如何来自己定义满足自己要求的视图或者控件呢?
1.首先
我们第一次创建第一个object-cApp的时候。我们需要把系统自己给我们的视图给删除掉
2.第二步,在程序的info.plist配置文件中把main storyboard file base name 属性设置为空
3.第3步 在AppDelegate.m中,手动创建window,以及一些程序运行的一些基本配置
//手动创建window
self.window = [[UIWindow alloc]initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height)];
self.window.backgroundColor = [UIColor redColor];
//创建根控制器
ViewController *view = [[ViewController alloc]init];
//绑定控制器
self.window.rootViewController = view;
//设置最先加载的视图
[self.window makeKeyAndVisible];
第4步 我们开始创建我们自己定义的视图,也就是图2中的MytestView视图,创建好了之后我们来实现一下
//自定义初始化方法
- (instancetype)initWithFrame:(CGRect)frame infoDictionary:(NSDictionary *)dict
{
//设置控件frame
self = [super initWithFrame:frame];
if (self) {
//传入字典。
[self setShowInfoView:dict];
}
return self;
}
- (void) setShowInfoView:(NSDictionary *)dict
{
//头像
UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(20, 20, 150, 150)];
//从dict字典中获取图片头像。并且显示到imageView
imageView.image = [UIImage imageNamed:dict[@"pic"]];
//将空图片控件添加到视图,之前写的是这样添加的[self.view addSubview:],这本身就是一个视图所有不用点view
[self addSubview:imageView];
//姓名
UILabel *labelName = [[UILabel alloc]initWithFrame:CGRectMake(CGRectGetMaxX(imageView.frame)+10, 20, 100, 44)];
//从dict字典中获取姓名字符串显示到lableName上
labelName.text = dict[@"name"];
//设置字体居中
labelName.textAlignment = NSTextAlignmentCenter;
labelName.textColor = [UIColor blackColor];
//将控件添加到视图
[self addSubview:labelName];
//介绍信息
UITextView *textView = [[UITextView alloc]initWithFrame:CGRectMake(20, CGRectGetMaxX(imageView.frame), 300, 150)];
//从dict字典中获取信息显示到介绍文本框中
textView.text = dict[@"Info"];
//设置能否编辑
textView.editable = NO;
//设置背景颜色
textView.textColor = [UIColor orangeColor];
[self addSubview:textView];
}
第5步 添加我们自定义的视图控件
NSDictionary *dic = @{@"pic":@"Steve Jobs.png",@"name":@"乔布什",@"Info":@"11月4日,瑞士著名钟表制造商天梭表宣布与五支NBA球队建立合作关系,进一步扩大了其作为NBA官方计时的承诺。这五支球队分别是:芝加哥公牛队、洛杉矶湖人队、迈阿密热火队、纽约尼克斯队和圣安东尼奥马刺队。"};
MyTestView *testView = [[MyTestView alloc]initWithFrame:self.view.frame infoDictionary:dic];
[self.view addSubview:testView];