iOS——简单的自定义view

来源:互联网 发布:淘宝买水果靠谱吗 知乎 编辑:程序博客网 时间:2024/04/30 02:31

一、代码写view

1、创建自定义view的文件


2、在.m中写初始化方法以及独有的方法:

- (instancetype)initWithFrame:(CGRect)frame {    self = [super initWithFrame:frame];    if (self) {        //定制View  可以做很多事情,比如添加手势等等        self.backgroundColor = [UIColor blueColor];        self.alpha = 0.5; // 可以设置透明度、颜色等等        self.userInteractionEnabled = YES; //设置为NO后,不再响应touch方法        self.multipleTouchEnabled = YES;        //控制子视图不能超出父视图的范围        self.clipsToBounds = YES;        //添加手势        UILongPressGestureRecognizer *longpress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longpressAction)];        [self addGestureRecognizer:longpress];    }    return self;}-(void)longpressAction {    NSLog(@"长按");}

3、在需要用到的地方导入自定义view的头文件,然后使用方法:

    myView *view = [[myView alloc]initWithFrame:CGRectMake(50, 150, 100, 100)];    [self.view addSubview:view];

二、加载Nib

1、创建文件以及view


2、.h中写方法:

+(testView *)initFromNib;

      .m中实现方法:

+(testView *)initFromNib{    //加载Nib    return [[[NSBundle mainBundle] loadNibNamed:@"testView" owner:self options:nil] lastObject];}- (instancetype)initWithCoder:(NSCoder *)coder{    self = [super initWithCoder:coder];    if (self) {        //想要什么view的属性,功能随便写        self.backgroundColor = [UIColor redColor];    }    return self;}
3、同理,加载这个view的时候的方法:

    testView *test = [testView initFromNib];    test.frame = CGRectMake(200, 150, 100, 100);    [self.view addSubview:test];



0 0
原创粉丝点击