Petral-UI是一个以Swift实现的 UI布局框架,以最少的代码,实现UI的搭建、属性设置以及布局控制。
Petral-UI主要是下面两个部分:
连续设置UIView的属性,例如
let nameLabel = UILabel.init()
.pt_frame(x: 0, y: 0, width: 80, height: 20)
.pt_text("姓名")
.pt_font(size: 14, bold: true)
.pt_textColor(UIColor.init(hexString: "#1f1f1f"));
通过直接调用.pt_为前缀的方法,直接连续设置View的UI属性,与调用系统方法的API类似。可实现对View的连续设置,减少代码。 现有的API可以基本满足UI设置,大家可以根据实际需要自行添加更多的API方法。
通过最少的代码,实现类似AutoLayout/Masory自动布局的功能,但代码量远少于这两个框架。
自动布局的使用步骤:
self.view.addSubview(nameLabel);
2.访问View的petralRestraint属性,通过以pt_为前缀的方法设置布局。
nameLabel.petralRestraint
.pt_topIn(self.view, distance: 10) // View的顶部与父View的距离为10
.pt_leftIn(self.view, distance: 20);// View的左边与父View的距离为20
View a与View b是属于同一层级的两个View,View b的位置可以由View a决定。
注意:如果a与b不是属于同一层级,调用以下方法将报错。
View b的左边与View a的距离是n
b.petralRestraint.pt_leftTo(a, distance: n)
View b的右边与View a的距离是n
b.petralRestraint.pt_rightTo(a, distance: n)
View b的顶部与View a的距离是n
b.petralRestraint.pt_topTo(a, distance: n)
View b的底部与View a的距离是n
b.petralRestraint.pt_bottomTo(a, distance: n)
View b的左边与View a的左边的水平位置一致
b.petralRestraint.pt_leftAs(a)
View b的右边与View a的右边的水平位置一致
b.petralRestraint.pt_rightAs(a)
View b的顶部与View a的顶部的水平位置一致
b.petralRestraint.pt_topAs(a)
View b的底部与View a的底部的水平位置一致
b.petralRestraint.pt_bottomAs(a)
b.petralRestraint.pt_xCenterAs(a)
View b的中间水平位置与View a的中间水平位置一致
b.petralRestraint.pt_yCenterAs(a)
View b的中间垂直位置与View a的中间垂直位置一致
b.petralRestraint.pt_centerAs(a)
View b的中间点与View a的中间点位置一致
View a与View b的父View,View b的位置可以由View a决定。
注意:如果a不是b的父View,调用以下方法将报错。
View b的左边与父View a的左边的距离为n
b.petralRestraint.pt_leftIn(a, distance: n)
View b的右边与父View a的y右边的距离为n
b.petralRestraint.pt_rightIn(a, distance: n)
View b的顶部与父View a的顶部的距离为n
b.petralRestraint.pt_topIn(a, distance: n)
View b的底部与父View a的底部的距离为n
b.petralRestraint.pt_bottomIn(a, distance: n)
View b的水平位置位于父View a的中间
b.petralRestraint.pt_xCenterIn(a)
View b的垂直位置位于父View a的中间
b.petralRestraint.pt_yCenterIn(a)
View b的水平和垂直位置位于父View a的中间
b.petralRestraint.pt_centerIn(a)
View b的固定宽度为n
b.petralRestraint.pt_width(n)
View b的固定高度为n
b.petralRestraint.pt_height(n)
View b的位置受到View a的制约,View c的位置受到View b的制约,若View a的位置或者大小发生改变,要保持之前的制约条件(Restraint),需要手动调用API方法a.petralRestraint.pt_updateDependeds();进行更新,使View b和View c的位置和大小发生改变。不手动调用该方法,将不主动实现UI的级联更新。
a.petralRestraint.pt_updateDependeds();
以下的情形会发生布局冲突,运行时抛出fatalError:
运行时发现fatalError的情形,请修改约束条件后重新运行。