这很可能(很可能,我会说)这不是在滚动视图中开始的。
考虑这个例子:
class TestSwitcherViewController: UIViewController {
var leadConstraint: NSLayoutConstraint!
override func viewDidLoad() {
super.viewDidLoad()
let colors: [UIColor] = [
// light red
UIColor(red: 1.0, green: 0.5, blue: 0.5, alpha: 1.0),
// light green
UIColor(red: 0.5, green: 1.0, blue: 0.5, alpha: 1.0),
// light blue
UIColor(red: 0.0, green: 0.5, blue: 1.0, alpha: 1.0),
// light orange
UIColor(red: 0.9, green: 0.7, blue: 0.5, alpha: 1.0),
// yellow
UIColor(red: 1.0, green: 1.0, blue: 0.0, alpha: 1.0),
]
var prevView: UIView!
// create a view for each color (a label with the view number as its text)
// for each of the views
// if it's the first one,
// constrain leading to view leading
// else
// constrain leading to previous view leading, constant 1.0, multiplier 2.0
var i = 1
colors.forEach { c in
let v = UILabel()
v.backgroundColor = c
v.text = "\(i)"
v.textAlignment = .center
v.layer.cornerRadius = 20
v.layer.masksToBounds = true
v.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(v)
v.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
v.widthAnchor.constraint(equalToConstant: 200.0).isActive = true
v.heightAnchor.constraint(equalToConstant: 400.0).isActive = true
if i == 1 {
leadConstraint = v.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 0.0)
leadConstraint.isActive = true
} else {
NSLayoutConstraint(item: v, attribute: .leading, relatedBy: .equal, toItem: prevView, attribute: .leading, multiplier: 2.0, constant: 1.0).isActive = true
}
prevView = v
i += 1
}
// add a pan gesture recognizer to the view
let pan = UIPanGestureRecognizer(target: self, action: #selector(self.didPan(_:)))
view.addGestureRecognizer(pan)
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
updateScales()
}
@objc func didPan(_ gesture: UIPanGestureRecognizer) -> Void {
let translation = gesture.translation(in: view)
// increment or decrement the leading anchor constant
let tmpX = leadConstraint.constant + (translation.x * 0.25)
// don't let it go past either side
leadConstraint.constant = min(max(tmpX, 0.0), view.frame.width - 200.0)
gesture.setTranslation(.zero, in: view)
updateScales()
}
func updateScales() -> Void {
view.subviews.forEach { v in
// percentage of distance from leading edge of label to 1/5th width of view
let pct = min(v.frame.origin.x / (view.frame.width * 0.2), 1.0)
let scale = 0.8 + 0.2 * pct
v.transform = .identity
v.transform = CGAffineTransform(scaleX: scale, y: scale)
}
}
}
它创建 5 个彩色视图(编号标签),并使用具有常量和乘数的前导锚将它们相互约束。它向视图添加了平移手势,因此当您向左或向右平移时,它会修改“底部”视图的前导约束的常量以将其向左/向右移动。这反过来又会移动其他视图...并且由于我们使用了一个乘数作为约束,所以当我们向右滑动时,移动会“增长”。
这是它在发布时的样子:
这是向右拖动一点后的样子:
显然,要复制 App Switcher 的所有功能需要做更多的工作,但它可能会让您顺利上路。