斯威夫特 5 版本:
import UIKit
class ViewController: UIViewController {
let collectionView: UICollectionView = {
let frame = CGRect(x: 0, y: 50, width: UIScreen.main.bounds.size.width, height: UIScreen.main.bounds.size.height - 50)
let col = UICollectionView(frame: frame, collectionViewLayout: UICollectionViewFlowLayout())
col.layer.borderColor = UIColor.red.cgColor
col.layer.borderWidth = 1.0
col.backgroundColor = UIColor.yellow
return col
}()
let switchView = UISwitch()
func switched(s: UISwitch){
let origin: CGFloat = s.on ? view.frame.height : 50
UIView.animate(withDuration: 0.35) {
self.collectionView.frame.origin.y = origin
}
}
override func viewDidLoad() {
super.viewDidLoad()
switchView.frame = CGRect(x: 0, y: 20, width: 40, height: 20)
switchView.addTarget(self, action: #selector(switched), forControlEvents: .valueChanged)
view.addSubview(switchView)
view.addSubview(collectionView)
}
}
我为您做了一个小演示:创建新项目并将代码写入ViewController.swift,仅此而已。认为有帮助
import UIKit
class ViewController: UIViewController {
let collectionView: UICollectionView = {
let frame = CGRect(x: 0, y: 50, width: UIScreen.mainScreen().bounds.size.width, height: UIScreen.mainScreen().bounds.size.height - 50)
let col = UICollectionView(frame: frame, collectionViewLayout: UICollectionViewFlowLayout())
col.layer.borderColor = UIColor.redColor().CGColor
col.layer.borderWidth = 1.0
col.backgroundColor = UIColor.yellowColor()
return col
}()
let switchView = UISwitch()
func switched(s: UISwitch){
let origin: CGFloat = s.on ? view.frame.height : 50
UIView.animateWithDuration(0.35) {
self.collectionView.frame.origin.y = origin
}
}
override func viewDidLoad() {
super.viewDidLoad()
switchView.frame = CGRect(x: 0, y: 20, width: 40, height: 20)
switchView.addTarget(self, action: #selector(switched), forControlEvents: .ValueChanged)
view.addSubview(switchView)
view.addSubview(collectionView)
}
}