iOS基于框架和自动布局
基于框架
- 通过(x,y,宽度,高度)进行定位。在多屏幕情况下需要进行大量计算和变量处理。
let customView = CustomView(frame: CGRect(x: 0, y: 0, width: 50, height: 50))
customView.translatesAutoresizingMaskIntoConstraints = true
自动调整掩码
是基于父视图的视图调整大小的行为。增加了一些动态性。
view.autoresizingMask = [.flexibleRightMargin]
自动布局
- 使用约束来设置视图之间的关系。视图的框架根据约束动态计算。这增加了理论上对性能的影响,但另一方面更加友好。
let customView = CustomView()
customView.translatesAutoresizingMaskIntoConstraints = false
customView.widthAnchor.constraint(equalToConstant: 50).isActive = true
...
自动布局引擎
measurement(subView->superView) -> layout(superView->subView)
![](https://istack.dev59.com/E0dTb.webp)
使用
view.translatesAutoresizingMaskIntoConstraints = false
来使用AutoLayout。在InterfaceBuilder中,默认情况下为
false
,在以编程方式创建视图时为
true
。如果您在代码中创建视图,则必须手动将其设置为
false
。
view.translatesAutoresizingMaskIntoConstraints = false // false for autolayout
view.topAnchor.constraint(equalTo: parentView.topAnchor, constant: 16).isActive = true
在编程中,可以使用AutoLayout和UITableView.automaticDimension
来设置func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat
,这样就不用考虑视图的高度。
当视图已经添加到打印视图中时,也可以设置约束。
parentView.addSubview(view)
view.topAnchor.constraint(equalTo: self.topAnchor, constant: 16).isActive = true
或者你得到
Terminating app due to uncaught exception 'NSGenericException', reason: 'Unable to activate constraint with anchors <> because they have no common ancestor. Does the constraint or its anchors reference items in different view hierarchies? That's illegal.'