如果我在故事板中有一个视图设置,是否有一种方法可以让我的视图(自定义宽度和高度)在按下按钮时从屏幕底部向上滑动?我希望屏幕只是叠加(这样你仍然可以按下屏幕下面的东西)。
我该如何设置?
func isChecked(){
let window = UIApplication.sharedApplication().keyWindow
window!.addSubview(collectionView)
let height: CGFloat = 250
let y = window!.frame.height - 250
collectionView.frame = CGRect(x: 0, y: window!.frame.height, width: window!.frame.width, height: height)
UIView.animateWithDuration(0.5, delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 1, options: .CurveEaseOut, animations: {
self.collectionView.frame = CGRectMake(0, y, self.collectionView.frame.width, self.collectionView.frame.height)
}, completion: nil)
}
func isUnchecked(){
let window = UIApplication.sharedApplication().keyWindow
UIView.animateWithDuration(0.3, animations: {
self.collectionView.frame = CGRectMake(0, window!.frame.height, self.collectionView.frame.width, self.collectionView.frame.height)
})
}
除了我在故事板中创建的视图外,有没有办法可以完成上面的操作?
答案 0 :(得分:6)
我为您做了一个小小的演示:创建新项目并在 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)
}
}
答案 1 :(得分:1)
SwiftStudier的答案更新为Swift 3:
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.isOn ? 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), for: .valueChanged)
view.addSubview(switchView)
view.addSubview(collectionView)
}
}