iOS开发之UI篇(1)—— UIView

来源:互联网 发布:linux 查看用户数 编辑:程序博客网 时间:2024/06/07 02:29

版本

Xcode 9.1

一、纯代码创建

#import "ViewController.h"@interface ViewController ()@end@implementation ViewController- (void)viewDidLoad {    [super viewDidLoad];    // 实例化一个UIView    UIView *view = [[UIView alloc] init];    /* ----- 基本设置 ----- */    // 设置尺寸大小及位置 (frame)    view.frame = CGRectMake(50, 50, 200, 200);    // 设置背景颜色    view.backgroundColor = [UIColor redColor];    // 设置透明度    view.alpha = 1;   // 透明度0~1    /* ----- layout设置 ----- */    //设置view自带CALayer图层的颜色(给CALayer设置的颜色,都要变成CGColor)//    view.layer.backgroundColor = [UIColor orangeColor].CGColor;    // 设置边框宽度    view.layer.borderWidth = 3;    // 设置边框颜色    view.layer.borderColor = [UIColor blackColor].CGColor;    // 设置圆角半径    view.layer.cornerRadius = 20;    /* 设置图片 *///    // 设置图片与设置阴影只能二选一,如果二者都要,只能再添加一个子layer (见下面代码)//    // 设置Layer渲染的内容//    view.layer.contents = (id)[UIImage imageNamed:@"23.jpg"].CGImage;//    // 切除超出父layer的部分//    view.layer.masksToBounds = YES;    /* 设置阴影 */    // 设置layer的阴影    view.layer.shadowOffset = CGSizeMake(20, 20);    // 设置layer颜色    view.layer.shadowColor = [UIColor lightGrayColor].CGColor;    // 设置layer阴影透明度    view.layer.shadowOpacity = 0.5;    /* ----- 添加一层子layer ----- */    // 实例化子layer    CALayer *subLayer = [[CALayer alloc]init];    // 设置frame    subLayer.frame = view.layer.bounds;    // 设置圆角    subLayer.cornerRadius = 100;    // 设置subLayer的渲染内容    subLayer.contents = (id)[UIImage imageNamed:@"23.jpg"].CGImage;    // 切除超出父layer的部分    subLayer.masksToBounds = YES;    // 添加到view.layer之上    [view.layer addSublayer:subLayer];    // 添加子视图到self.view上    [self.view addSubview:view];}@end


效果图
效果图

二、使用XIB

假如新建了一个Single View App,接着创建一个XIB文件:


1
1


2
2


3
3

然后在Xcode右侧编辑栏可以直接编辑view的属性和id,例如设置view的frame、边框、阴影等:


属性栏
属性栏


id栏
id栏

可以在xib里面创建多个view,等下代码调用的时候会用到:


一个xib里创建了两个view
一个xib里创建了两个view

然后使用代码调用:

    // 从xib(名称为View)实例化view    UIView *view1 = [[[NSBundle mainBundle] loadNibNamed:@"View" owner:self options:nil] firstObject];    UIView *view2 = [[[NSBundle mainBundle] loadNibNamed:@"View" owner:self options:nil] objectAtIndex:1];    // 添加view到self.view    [self.view addSubview:view1];    [self.view addSubview:view2];
  • loadNibNamed: owner: options: 方法返回来的是一个NSArray数组,因为之前创建了两个view,所以数组里面有两个对象元素。
  • 因为使用了Single View App模板,所以controller自带了一个view(self.view),所以我们创建的view要添加上去(addSubview)。

三、使用storyboard

因为使用了Single View App模板,所以工程里默认包含有一个main.storyboard,点击之。
在右侧编辑栏底部搜索UIView,找到UIView并拖入self.view中:


然后就可以向xib中那样设置属性和id了


设置尺寸
设置尺寸


设置属性
设置属性


设置其他属性
设置其他属性

我们可以把在storyboard里面创建的view关联到代码中,以便使用代码编辑:


因为是在storyboard的viewController里面创建的view,而程序启动时,窗口显示的view就是我们所编辑的viewController的root view(根视图),所以不用addSubview操作。

用代码编辑关联过去的view:

    // 编辑从storyboard创建的myView    self.myView.layer.borderColor = [UIColor yellowColor].CGColor;

效果图:


原创粉丝点击