自定义控件程序运行流程

1、自定义控件

  • 1.1 CHDataView.h

//
// 文 件 名:CHDataView.h
//
// 版权所有:Copyright © 2018年 Lelight. All rights reserved.
// 创 建 者:leLight
// 创建日期:2018/8/4.
// 文档说明:
// 修 改 人:
// 修改日期:
//

#import <Foundation/Foundation.h>

@interface CHDataView : UIView

/** 数据模型 */
@property (nonatomic, strong) CHDataItem *dataItem;

@end
  • 1.2 CHDataView.m

//
// 文 件 名:CHDataView.m
//
// 版权所有:Copyright © 2018年 Lelight. All rights reserved.
// 创 建 者:leLight
// 创建日期:2018/6/12.
// 文档说明:
// 修 改 人:
// 修改日期:
//

#import "CHDataView.h"
#import "CHDataItem.h"

@interface CHDataView ()

/** 标题按钮 */
@property (strong, nonatomic) UILabel *name;
/** 按钮 */
@property (strong, nonatomic) UIButton *button;

@end

@implementation CHDataView

#pragma mark ***************************** 视图 ***********************************************
/************ 将需要在本视图显示的控件在这里添加进去 *****************************/
- (id)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        
        self.name = [[UILabel alloc] init];
        self.button = [[UIButton alloc] init];
    }
    return self;
}

/************ 设置模型数据 *****************************/
- (void)setDataItem:(CHDataItem *)dataItem {
    _dataItem = dataItem;
  
    self.name.text = dataItem.deviceName;
    [self.button setTitle:dataItem.deviceMac forState:UIControlStateNormal];;
    
}

/************ 设置本页面各子控件的布局 *****************************/
- (void)layoutSubviews {
    [super layoutSubviews];
    
    self.name.frame = CGRectMake(0, 50, 200, 50);
    self.button.frame = CGRectMake(0, 110, 200, 50);
}

/************ 头部颜色渐变 *****************************/
- (void) drawRect:(CGRect)rect{
 
    // 头部标题背景颜色渐变
    CAGradientLayer *headerLayer = [CAGradientLayer layer];
    headerLayer.startPoint = CGPointMake(0, 0.5); //(0,0)表示从左上角开始变化。默认值是(0.5,0.0)表示从x轴为中间,y为顶端的开始变化
    headerLayer.endPoint = CGPointMake(1, 0.5); //(1,1)表示到右下角变化结束。默认值是(0.5,1.0)  表示从x轴为中间,y为低端的结束变化
    headerLayer.colors = [NSArray arrayWithObjects:(id)[UIColor whiteColor].CGColor,(id)[UIColor yellowColor].CGColor, (id)[UIColor whiteColor].CGColor, nil];
    // layer.locations = @[@0.0f, @1.0f];//渐变颜色的区间分布,locations的数组长度和color一致,这个值一般不用管它,默认是nil,会平均分布
    headerLayer.frame = self.button.bounds;
    [self.button.layer insertSublayer:headerLayer atIndex:0];
    [self.button.layer addSublayer:headerLayer];
}

@end

2、自定义控件中的实际执行顺序

// 01 将需要在本视图显示的控件在这里添加进去
- (id)initWithFrame:(CGRect)frame;
// 02 设置模型数据
- (void)setDataItem:(CHDataItem *)dataItem;
// 03 设置本页面各子控件的布局
- (void)layoutSubviews;
// 04 描绘控件的层级
- (void) drawRect:(CGRect)rect;
原文地址:https://www.cnblogs.com/CH520/p/9419365.html