iOS intrinsicContentSize内置尺寸

1,262 阅读1分钟

intrinsicContentSize 顾名思义为控件的内置内容尺寸

@property(nonatomic, readonly) CGSize intrinsicContentSize API_AVAILABLE(ios(6.0));

// call this when something changes that affects the intrinsicContentSize.  Otherwise UIKit won't notice that it changed.
- (void)invalidateIntrinsicContentSize API_AVAILABLE(ios(6.0)); 

一个控件在项目中的展现一般由两种东西来决定,一个是坐标,一个是尺寸大小

控件的内置大小可以通过其内的intrinsicContentSize属性来更改

但在日常开发中,对于UILabel或UIButton等控件来说,给定其坐标而不给尺寸大小,只是用sizeToFit同样可以将视图展现出来,就是因为UILabel或UIButton已经由其控件的展示内容计算决定了它的控件合理的内置尺寸大小


但对于某些特定情况如在MBProgressHUD 添加自定义视图时,若给定视图为不确定大小的图片,展示出来的效果就很差强人意,这时就需要更改对应View中的内置大小来适配合适的尺寸

/**
 * The UIView (e.g., a UIImageView) to be shown when the HUD is in MBProgressHUDModeCustomView.
 * The view should implement intrinsicContentSize for proper sizing. For best results use approximately 37 by 37 pixels.
 */
@property (strong, nonatomic, nullable) UIView *customView;

MBProgressHUD 中已经提示需执行view的intrinsicContentSize属性 The view should implement intrinsicContentSize for proper sizing.


intrinsicContentSize只读属性,外部无法直接给定更改的尺寸 此时需要在相应View中指定 intrinsicContentSize 方法,重写 UIView 中的 - (CGSize)intrinsicContentSize 方法,来更改相应控件的内置尺寸大小,告知系统值已改变,这时的view的展示大小就可符合相应的设计要求

- (CGSize)intrinsicContentSize{
    return CGSizeMake(width, height);
}