Answers:
如您所说,如果您知道如何在代码中进行操作,那么您已经在情节提要中知道如何进行操作。这是完全相同的约束,但是您是在视觉上而不是在代码中创建它们。
选择一个视图及其超级视图。
选择“编辑器”->“固定”->“宽度”,将宽度限制为等于超级视图的宽度(实际上,画布底部的“固定”弹出对话框在此处效果最佳)。
编辑约束并将“乘数”设置为所需的分数,例如0.42。其他观点也是如此。
随着Apple推出UIStackView,它使工作变得非常容易。
方法1:使用笔尖/ StoryBoard:
您只需要在界面生成器中添加三个视图并将它们嵌入到stackview中
Xcode►编辑器►嵌入►StackView
选择stackView并使用safeArea通过前导,尾随,顶部和等高给出约束
单击以进入属性检查器区域并 设置StackView水平和分布以按比例填充
[ 3
方法2:以编程方式:
import UIKit
class StackViewProgramatically: UIViewController {
var propotionalStackView: UIStackView!
///Initially defining three views
let redView: UIView = {
let view = UIView()//taking 42 % initially
view.frame = CGRect(x: 0, y: 0, width: 42 * UIScreen.main.bounds.width/100, height: UIScreen.main.bounds.height)
view.backgroundColor = .red
return view
}()
let greenView: UIView = {
let view = UIView()//taking 42* initially
view.frame = CGRect(x: 42 * UIScreen.main.bounds.width/100, y: 0, width: 25 * UIScreen.main.bounds.width/100, height: UIScreen.main.bounds.height)
view.backgroundColor = .green
return view
}()
let blueView: UIView = {
let view = UIView()//taking 33*initially
view.frame = CGRect(x: 67 * UIScreen.main.bounds.width/100, y: 0, width: 33 * UIScreen.main.bounds.width/100, height: UIScreen.main.bounds.height)
view.backgroundColor = .blue
return view
}()
///Changing UIView frame to supports landscape mode.
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransition(to: size, with: coordinator)
DispatchQueue.main.async {
self.redView.frame = CGRect(x: 0, y: 0, width: 42 * self.widthPercent, height: self.screenHeight)
self.greenView.frame = CGRect(x: 42 * self.widthPercent, y: 0, width: 25 * self.widthPercent, height: self.screenHeight)
self.blueView.frame = CGRect(x: 67 * self.widthPercent, y: 0, width: 33 * self.widthPercent, height: self.screenHeight)
}
}
override func viewDidLoad() {
super.viewDidLoad()
//Adding subViews to the stackView
propotionalStackView = UIStackView()
propotionalStackView.addSubview(redView)
propotionalStackView.addSubview(greenView)
propotionalStackView.addSubview(blueView)
propotionalStackView.spacing = 0
///setting up stackView
propotionalStackView.axis = .horizontal
propotionalStackView.distribution = .fillProportionally
propotionalStackView.alignment = .fill
view.addSubview(propotionalStackView)
}
}
//MARK: UIscreen helper extension
extension NSObject {
var widthPercent: CGFloat {
return UIScreen.main.bounds.width/100
}
var screenHeight: CGFloat {
return UIScreen.main.bounds.height
}
}
输出:
适用于风景和肖像
演示项目-https://github.com/janeshsutharios/UIStackView-with-constraints
我认为可以对此进行更详细的说明,以便可以更轻松地将其应用于需要在超级视图中固定比例布局的任意数量的视图。
SuperView.Leading
SuperView.Height
SuperView.Height
left
在其邻居的右边left
在其邻居的右边right
到SuperView.Trailing
Top Layout Guide.Top
和来定义其非固定高度Top Layout Guide.bottom
。在上面的答案中,请注意,这也可以通过将相邻视图设置为相等的高度来完成。