IOS 纯代码自定义UIView案例

objectivec 复制代码
#import <UIKit/UIKit.h>

NS_ASSUME_NONNULL_BEGIN

@interface OrderAfterPeriodSelectNumView : UIView
//左边标题
@property (nonatomic,strong) UILabel *titleLab;
//数量
@property (nonatomic,strong) UILabel *numLab;

@end
objectivec 复制代码
#import "OrderAfterPeriodSelectNumView.h"
@interface OrderAfterPeriodSelectNumView()
@property (nonatomic, assign) CGFloat titleLabWidth;
@end

@implementation OrderAfterPeriodSelectNumView

#pragma mark - 原始初始化方法

// 1、首先调用init方法
- (instancetype)init{
    if (self = [super init]) {
        [self initUI];
    }
    return self;
}
  
// 2、然后调用initWithFrame方法
- (instancetype)initWithFrame:(CGRect)frame{
    if (self =[super initWithFrame:frame]) {
        [self initUI];
    }
    return self;
}
// 初始化UI控件
- (void) initUI{
    UILabel *titleLab = [[UILabel alloc] init];
    titleLab.textColor = [UIColor colorWithHexString:@"333333"];
    titleLab.font = [UIFont systemFontOfSize:14];
    titleLab.textAlignment = NSTextAlignmentLeft;
    titleLab.text = @"退款数量";
    [self addSubview:titleLab];
    _titleLab = titleLab;
    
    UILabel *numLab = [[UILabel alloc] init];
    titleLab.textColor = [UIColor colorWithHexString:@"333333"];
    numLab.font = [UIFont systemFontOfSize:14];
    numLab.textAlignment = NSTextAlignmentRight;
    numLab.text = @"0";
    [self addSubview:numLab];
    _numLab = numLab;
    //获取字符串的宽高
    CGRect rect = [titleLab.text boundingRectWithSize:CGSizeMake(SCREENWIDTH, MAXFLOAT) options:NSStringDrawingTruncatesLastVisibleLine | NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:@{NSFontAttributeName: [UIFont systemFontOfSize:14]} context:nil];
    _titleLabWidth = rect.size.width;

}
// 设置UI控件的frame
- (void)layoutSubviews{
    [super layoutSubviews];
    // 1.获取当前控件的尺寸
    CGFloat width = self.frame.size.width;
    CGFloat height = self.frame.size.height;
    
    // 2.设置子控件的frame
    self.titleLab.frame = CGRectMake(16, 0, self.titleLabWidth, height);
    self.numLab.frame = CGRectMake(16+self.titleLabWidth, 0, width - (16+self.titleLabWidth+16), height);
    
}

@end

添加到UIStackView

objectivec 复制代码
OrderAfterPeriodSelectNumView *numView = [[OrderAfterPeriodSelectNumView alloc] init];
[numView mas_makeConstraints:^(MASConstraintMaker *make) {
     make.height.equalTo(@(50));
 }];
self.numView = numView;
[self.stackView addArrangedSubview:numView];
相关推荐
齐生13 小时前
网络知识点 - TCP/IP 四层模型知识大扫盲
笔记·ios
IT技术分享社区4 小时前
数码资讯:iPhone 18 Pro,十大升级细节浮出水面
ios·手机·iphone
嵌入式学习菌5 小时前
https不校验证书实现及https接口实现
ios·iphone
harmful_sheep6 小时前
mac生效的终端查看
macos
iOS门童1 天前
macOS 应用"已损坏"无法打开?一文搞懂 Gatekeeper 与解决方案
macos
NPE~1 天前
[工具分享]Maccy —— 优雅的 macOS 剪贴板历史管理工具
macos·教程·工具·实用工具
忙碌5441 天前
OpenTelemetry实战指南:构建云原生全链路可观测性体系
ios·flink·apache·iphone