Swift 教程之UIStackview 01 基础使用
简介
UIStackView是支持线性流式界面布局集合视图,他支持column和row两种方向。UIStackView依托于Auto Layout的强大布局功能呢,可以根据不同设备方向、屏幕大小、容器大小来实现动态界面布局。
UIStackView通过arrangedSubviews属性来管理子视图。这些子视图根据UIStackview的axis(轴)进行排列。另外我们还需要axis、distrubtion、alignment、spacing等参数来完成节目布局。
您负责定义UIStackView的大小和位置,UIStackView负责管理其内部的布局和大小。
效果图
1. 定义一个stackview
fileprivate let stackView: UIStackView = {
let stack = UIStackView()
stack.translatesAutoresizingMaskIntoConstraints = false
stack.distribution = .fillEqually
stack.axis = .vertical
stack.spacing = 40
return stack
}()
2. 配置一下显示内容
view.addSubview(stackView)
stackView.heightAnchor.constraint(equalToConstant: view.frame.height - 100).isActive = true
stackView.widthAnchor.constraint(equalToConstant: view.frame.width - 40).isActive = true
stackView.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
stackView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
// Do any additional setup after loading the view.
let iv1 = UIImageView(image: UIImage(named: "001_jydc.jpg"))
let iv2 = UIImageView(image: UIImage(named: "002_yqch.jpg"))
let iv3 = UIImageView(image: UIImage(named: "003_tyqf.jpg"))
stackView.addArrangedSubview(iv1)
stackView.addArrangedSubview(iv2)
stackView.addArrangedSubview(iv3)
/*
iv1.contentMode = .scaleAspectFit
iv2.contentMode = .scaleAspectFit
iv3.contentMode = .scaleAspectFit
*/
iv1.contentMode = .scaleAspectFill
iv2.contentMode = .scaleAspectFill
iv3.contentMode = .scaleAspectFill
iv1.clipsToBounds = true
iv2.clipsToBounds = true
iv3.clipsToBounds = true
iv1.layer.cornerRadius = 40
iv2.layer.cornerRadius = 40
iv3.layer.cornerRadius = 2