实现具有 intrinsic content size 功能的自定义视图类(支持 xib/sb 使用)

271 篇文章 0 订阅
11 篇文章 0 订阅

对于 intrinsic content size 不熟悉的童鞋,建议先看一下下面这篇文章,再开始本文的阅读

只有 20% 的 iOS 程序员能看懂:详解 intrinsicContentSize 及 约束优先级/content Hugging/content Compression Resistance

iOS 开发中经常需要使用 xib/storyboard 配合 AutoLayout 来做一些界面的布局适配工作,其中 UILabel、UIButton、UIImageView 等系统控件,在使用相对布局时候只指定位置不指定大小也可以正常工作,原因就是其借助 intrinsic content size 功能加了几条隐式的约束,辅助确定其大小。

那么我们不禁发问,我们自定义的视图类能否也能做到像这几个系统控件一样,在使用 xib/storyboard 时简化我们设置布局,特别是简化对于“出现多个视图放不下需要考虑优先压缩那个视图”的处理,只需要通过控制 content compression resistance 优先级就可以呢?

答案是肯定的,下面介绍具体怎么操作。


现在假设系统没有 UILabel,我自己实现一个具有 Intrinsic Content Size 功能的自定义视图,命名为 SmartLabel。

  • 首先,创建继承自 UIView 的视图类 SmartLabel,为了简化,只支持设置 title(字体、颜色、高度暂时写死)

    @interface SmartLabel : UIView
    
    @property (nonatomic, copy) NSString *title;
    
    @end
  • 接着,来看下 .m 中的实现

    @interface SmartLabel ()
    
    @property (nonatomic, strong) UILabel *titleLabel;
    @property (nonatomic, strong) UILabel *tipLabel;
    
    @end
    
    @implementation SmartLabel
    
    - (instancetype)initWithCoder:(NSCoder *)aDecoder {
        if (self = [super initWithCoder:aDecoder]) {
            [self commonInit];
        }
    
        return self;
    }
    
    - (instancetype)initWithFrame:(CGRect)frame {
        if (self = [super initWithFrame:frame]) {
            [self commonInit];
        }
    
        return self;
    }
    
    - (void)commonInit {
        self.backgroundColor = [UIColor redColor];
    
        UILabel *titleLabel = [UILabel new];
        titleLabel.font = [self labelsFont];
        titleLabel.textColor = [UIColor greenColor];
        titleLabel.text = @"";
        self.titleLabel = titleLabel;
        [self addSubview:self.titleLabel];
        [self.titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.leading.top.trailing.equalTo(self);
            make.height.equalTo(@25);
        }];
        [self.titleLabel setContentCompressionResistancePriority:1 forAxis:UILayoutConstraintAxisHorizontal];
    
        UILabel *tipLabel = [UILabel new];
        tipLabel.font = [self labelsFont];
        tipLabel.textColor = [UIColor blueColor];
        tipLabel.text = @"";
        self.tipLabel = tipLabel;
        [self addSubview:self.tipLabel];
        [self.tipLabel mas_makeConstraints:^(MASConstraintMaker *make) {
                make.leading.trailing.bottom.equalTo(self);
                make.top.equalTo(self.titleLabel.mas_bottom);
        }];
        [self.tipLabel setContentCompressionResistancePriority:0 forAxis:UILayoutConstraintAxisHorizontal];
    }
    
    - (void)layoutSubviews {
        [super layoutSubviews];
    
        self.tipLabel.text = [NSString stringWithFormat:@"width: %.0f", self.size.width];
    }
    
    - (void)setTitle:(NSString *)title {
        _title = [title copy];
    
        self.titleLabel.text = _title;
    
        [self invalidateIntrinsicContentSize];
    }
    
    - (CGSize)intrinsicContentSize {
        CGFloat titleLabelWidth = [_title textSizeForOneLineWithFont:[self labelsFont]].width;
    
        return CGSizeMake(titleLabelWidth, 50);
    }
    
    - (UIFont *)labelsFont {
        static UIFont *s_labelsFont = nil;
    
        if (!s_labelsFont) {
            s_labelsFont = [UIFont systemFontOfSize:12.f];
        }
    
        return s_labelsFont;
    }
    
    @end

    其中重写 initWithCoder: 是为了支持 xib/storyboard 中使用
    添加一个 tipLabel 方便查看当前视图的宽度(方便测试效果而已)
    其中 titleLabel 和 tipLabel 本身也有 intrinsic content size 生成的隐式约束约束,为了不影响自定义视图水平方向上的隐式约束,将其水平方向的 content compression resistance 优先级设置为 0。
    其中字体、颜色、高度各种写死,只是为了简化,自己实现自定义视图时最好根据需要可配置。
    当一些可能影响 intrinsic content size 的属性发生变化,需要调用 [self invalidateIntrinsicContentSize]; 触发重新根据 -(CGSize)intrinsicContentSize; 设置隐式约束。

  • 最后,我们来测试一下这个视图在 xib 中的使用
    这里写图片描述


    这里写图片描述

    注意图中标注的 6 个地方,由于系统控件可以直接使用 Intrinsic Size - Default (System Defined),但是自定义视图需要选择 Placeholder,里面的宽高可以先随便设置,正如其名字所属,只是先保证 xib/storyboard 中的相对布局不报错,具体可以看下 IB 中说明如下图。
    这里写图片描述

接着看下测试代码:

@interface SmartLabelTestVC ()

@property (weak, nonatomic) IBOutlet SmartLabel *smartView;

@property (nonatomic, strong) NSTimer *repeatTimer;

@end

@implementation SmartLabelTestVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.

    self.view.backgroundColor = [UIColor whiteColor];

    if ([self respondsToSelector:@selector(edgesForExtendedLayout)]) {
        self.edgesForExtendedLayout = UIRectEdgeNone;
    }

    @weakify(self);
    self.repeatTimer = [NSTimer scheduledTimerWithTimeInterval:0.3 repeats:YES block:^(NSTimer *timer) {
        @strongify(self);
        [self appendTextToSmartView];
        if (self.smartView.title.length >= 60) {
            [timer invalidate];
            timer = nil;
        }
    }];
    [[NSRunLoop mainRunLoop] addTimer:self.repeatTimer forMode:NSRunLoopCommonModes];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];

    [self.navigationController setNavigationBarHidden:NO animated:animated];
}

- (void)appendTextToSmartView {
    static int s_num = 0;

    s_num++;
    if (s_num >= 10) {
        s_num = 0;
    }

    self.smartView.title = [NSString stringWithFormat:@"%@%d", self.smartView.title ? : @"", s_num];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)dealloc {
    NSLog (@"%@ dealloc", [self class]);
}

@end

再来看下运行后的效果:
这里写图片描述

再修改一下两者的水平方向上的 content compression resistance 优先级,看下运行效果:
这里写图片描述


总结下来,自定义视图支持 intrinsic content size 后也可以像系统控件一样在 xib/storyboard 中简化约束的设置,通过控制 content hugging/content compression resistance 的优先级就可以很方便的控制特殊场景下的视图布局。这样可以将原本需要写在 ViewController 中的繁杂适配逻辑解耦到各个 View 内部,避免了每个使用到的 ViewController 中都要写繁杂的适配逻辑,所以没有使用的小伙伴可以考虑大刀耍起来了,珍爱生命,点滴做起~

代码地址:https://github.com/BenXia/AutoLayoutDemo

由于Intrinsic Biophysical Mechanism (IBM)模型是一个复杂的理论框架,其实现需要大量的数学公式和计算,而且需要考虑多个物理过程的相互作用。因此,这个模型的实现比较复杂,需要一定的数学和编程技能。 这里提供一个简单的例子,演示如何使用Python实现IBM模型的一部分功能。具体来说,我们将实现IBM模型的水文过程部分,包括蒸散发,入渗,径流,以及土壤水分的动态变化。 首先,我们定义一个包含IBM模型中主要参数的: ```python class IBMParameters: def __init__(self, solar_radiation, temperature, precipitation, vegetation_cover, soil_properties): self.solar_radiation = solar_radiation self.temperature = temperature self.precipitation = precipitation self.vegetation_cover = vegetation_cover self.soil_properties = soil_properties ``` 其中,solar_radiation表示太阳辐射,temperature表示温度,precipitation表示降水,vegetation_cover表示植被覆盖率,soil_properties表示土壤性质。这些参数将用于计算IBM模型中的水文过程。 接下来,我们定义一个IBM模型的水文过程: ```python class IBMHydrology: def __init__(self, parameters): self.parameters = parameters self.soil_moisture = 0.5 self.runoff = 0.0 def calculate_evapotranspiration(self): evapotranspiration = self.parameters.vegetation_cover * self.parameters.temperature return evapotranspiration def calculate_infiltration(self): infiltration_capacity = self.parameters.soil_properties * self.soil_moisture infiltration = min(infiltration_capacity, self.parameters.precipitation) return infiltration def calculate_runoff(self): excess_precipitation = max(0, self.parameters.precipitation - self.calculate_infiltration()) self.runoff += excess_precipitation def update_soil_moisture(self): soil_moisture_change = self.calculate_infiltration() - self.calculate_evapotranspiration() - self.runoff self.soil_moisture += soil_moisture_change ``` 这个中包含了IBM模型中的水文过程部分,包括蒸散发,入渗,径流,以及土壤水分的动态变化。在初始化时,我们将土壤水分设置为0.5,径流设置为0。然后,我们分别实现了计算蒸散发、入渗、径流、土壤水分变化的函数。 最后,我们可以使用这个来模拟IBM模型中的水文过程。例如,我们可以定义一个IBM模型参数对象,然后创建一个IBM水文过程对象,并进行模拟: ```python parameters = IBMParameters(solar_radiation=500, temperature=25, precipitation=50, vegetation_cover=0.5, soil_properties=0.2) hydrology = IBMHydrology(parameters) for i in range(100): hydrology.calculate_runoff() hydrology.update_soil_moisture() print(hydrology.soil_moisture) print(hydrology.runoff) ``` 在这个例子中,我们模拟了100个时间步长,计算了土壤水分和径流的变化。在每个时间步长中,我们首先计算径流,然后更新土壤水分。最后,我们输出了最终的土壤水分和径流的值。 需要注意的是,这个例子是非常简化的,只包含了IBM模型中的水文过程部分。实际上,IBM模型还包含了地形演化、植被生长和土壤侵蚀等多个过程,需要更加复杂的模型和算法来实现
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值