AutoLayoutDemo

- 假设UI给的效果图是6p的,图片在6p上是100*100的,在别的屏幕按比例缩放。
- label的字数不固定。
- label可能显示或隐藏,cell需要根据label的显示和隐藏去适应高度。
先来一步步来实现上面三个需求....
#####一、子控件根据父控件比例缩放
1、先在xib中拖出上面两个控件,选中图片,设置距离cell上面和左边的边距都为10,图片的x和y已经确定了,这里就不上图了,大家应该知道。
2、为了图片不变形,先设置图片相对自身的宽高比,选中图片,往自身拖出约束,选择Aspect Ratio







- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
self.example1TableView.estimatedRowHeight = 100;
}
#####三、设置约束优先级 先简单介绍一下约束优先级,具有优先级1000(UILayoutPriorityRequired)的约束为强制约束(Required Constraint),也就是必须要满足的约束;优先级小于1000的约束为可选约束(Optional Constraint)。默认创建的是强制约束。它分为 高优先级:UILayoutPriorityDefaultHigh, 低优先级:UILayoutPriorityDefaultLow, 内置的最低优先级:UILayoutPriorityFittingSizeLevel
typedef float UILayoutPriority;
static const UILayoutPriority UILayoutPriorityRequired NS_AVAILABLE_IOS(6_0) = 1000; // A required constraint. Do not exceed this.
static const UILayoutPriority UILayoutPriorityDefaultHigh NS_AVAILABLE_IOS(6_0) = 750; // This is the priority level with which a button resists compressing its content.
static const UILayoutPriority UILayoutPriorityDefaultLow NS_AVAILABLE_IOS(6_0) = 250; // This is the priority level at which a button hugs its contents horizontally.
static const UILayoutPriority UILayoutPriorityFittingSizeLevel NS_AVAILABLE_IOS(6_0) = 50; // When you send -[UIView systemLayoutSizeFittingSize:], the size fitting most closely to the target size (the argument) is computed. UILayoutPriorityFittingSizeLevel is the priority level with which the view wants to conform to the target size in that computation. It's quite low. It is generally not appropriate to make a constraint at exactly this priority. You want to be higher or lower.
现在我们想当label隐藏时图片距离cell的底部也为10,现在就需要再添加一条图片距离cell底部为10的下边距,这时候我们发现会有冲突,选中这条约束把优先级设置得低一些,会发现冲突消失了,约束变成了虚线,把之前图片相对label的边距的约束拖到.h中作为cell的属性。

cell.imageBotton.priority = cell.label.hidden ? UILayoutPriorityDefaultLow : UILayoutPriorityDefaultHigh;
当label隐藏时把优先级设置为UILayoutPriorityDefaultLow,显示时设置UILayoutPriorityDefaultHigh,只要是比图片底部相对父控件边距那条约束低就行了。 这里有一个注意点:
- 不允许将优先级由小于1000的值改为1000,例如,如果将优先级由250修改为1000,则会抛出异常,控制台会打印以下:
所有操作都做完了,现在运行效果如下:
最后是这次的代码: https://github.com/ShelinShelin/AutoLayoutDemo 之前的一些例子请点击: https://github.com/ShelinShelin 欢迎右上角⭐️Star,谢谢!

