当前位置:   article > 正文

IOS 纯代码自定义UIView案例

IOS 纯代码自定义UIView案例
  1. #import <UIKit/UIKit.h>
  2. NS_ASSUME_NONNULL_BEGIN
  3. @interface OrderAfterPeriodSelectNumView : UIView
  4. //左边标题
  5. @property (nonatomic,strong) UILabel *titleLab;
  6. //数量
  7. @property (nonatomic,strong) UILabel *numLab;
  8. @end

  1. #import "OrderAfterPeriodSelectNumView.h"
  2. @interface OrderAfterPeriodSelectNumView()
  3. @property (nonatomic, assign) CGFloat titleLabWidth;
  4. @end
  5. @implementation OrderAfterPeriodSelectNumView
  6. #pragma mark - 原始初始化方法
  7. // 1、首先调用init方法
  8. - (instancetype)init{
  9. if (self = [super init]) {
  10. [self initUI];
  11. }
  12. return self;
  13. }
  14. // 2、然后调用initWithFrame方法
  15. - (instancetype)initWithFrame:(CGRect)frame{
  16. if (self =[super initWithFrame:frame]) {
  17. [self initUI];
  18. }
  19. return self;
  20. }
  21. // 初始化UI控件
  22. - (void) initUI{
  23. UILabel *titleLab = [[UILabel alloc] init];
  24. titleLab.textColor = [UIColor colorWithHexString:@"333333"];
  25. titleLab.font = [UIFont systemFontOfSize:14];
  26. titleLab.textAlignment = NSTextAlignmentLeft;
  27. titleLab.text = @"退款数量";
  28. [self addSubview:titleLab];
  29. _titleLab = titleLab;
  30. UILabel *numLab = [[UILabel alloc] init];
  31. titleLab.textColor = [UIColor colorWithHexString:@"333333"];
  32. numLab.font = [UIFont systemFontOfSize:14];
  33. numLab.textAlignment = NSTextAlignmentRight;
  34. numLab.text = @"0";
  35. [self addSubview:numLab];
  36. _numLab = numLab;
  37. //获取字符串的宽高
  38. CGRect rect = [titleLab.text boundingRectWithSize:CGSizeMake(SCREENWIDTH, MAXFLOAT) options:NSStringDrawingTruncatesLastVisibleLine | NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:@{NSFontAttributeName: [UIFont systemFontOfSize:14]} context:nil];
  39. _titleLabWidth = rect.size.width;
  40. }
  41. // 设置UI控件的frame
  42. - (void)layoutSubviews{
  43. [super layoutSubviews];
  44. // 1.获取当前控件的尺寸
  45. CGFloat width = self.frame.size.width;
  46. CGFloat height = self.frame.size.height;
  47. // 2.设置子控件的frame
  48. self.titleLab.frame = CGRectMake(16, 0, self.titleLabWidth, height);
  49. self.numLab.frame = CGRectMake(16+self.titleLabWidth, 0, width - (16+self.titleLabWidth+16), height);
  50. }
  51. @end

添加到UIStackView

  1. OrderAfterPeriodSelectNumView *numView = [[OrderAfterPeriodSelectNumView alloc] init];
  2. [numView mas_makeConstraints:^(MASConstraintMaker *make) {
  3. make.height.equalTo(@(50));
  4. }];
  5. self.numView = numView;
  6. [self.stackView addArrangedSubview:numView];

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Monodyee/article/detail/502972
推荐阅读
相关标签
  

闽ICP备14008679号