Swift 中的动画显示和隐藏视图
Posted
技术标签:
【中文标题】Swift 中的动画显示和隐藏视图【英文标题】:Animation show and hide view in Swift 【发布时间】:2018-06-14 06:58:30 【问题描述】:我有这个功能:
func showwAndHideFilterMenu(category : Int)
if showFilterMenu == false
UIView.animate(withDuration: 0.6, delay: 0, options: .curveEaseInOut, animations:
self.filterView.isHidden = false
self.showFilterMenu = true
) (isCompleted) in
else
UIView.animate(withDuration: 0.6, delay: 0, options: .curveEaseInOut, animations:
self.filterView.isHidden = true
self.self.showFilterMenu = false
) (isCompleted) in
我有一个显示和隐藏视图的功能。我想添加一个动画来显示/隐藏这个视图。怎么做?动画的方向是从上到下。
有人知道怎么做吗?
【问题讨论】:
操纵 alpha 值,并在完成块中使用 isHidden 属性。 【参考方案1】:您需要操作 alpha 属性,而不是 UIView 淡入淡出动画的 isHidden 属性。
尝试以下方法:
func showAndHideFilterMenu(category : Int)
if showFilterMenu == false
self.filterView.alpha = 0.0
self.filterView.isHidden = false
self.showFilterMenu = true
UIView.animate(withDuration: 0.6,
animations: [weak self] in
self?.filterView.alpha = 1.0
)
else
UIView.animate(withDuration: 0.6,
animations: [weak self] in
self?.filterView.alpha = 0.0
) [weak self] _ in
self?.filterView.isHidden = true
self?.showFilterMenu = false
【讨论】:
对于从上到下的动画,请使用@ios Geek 的答案【参考方案2】:确保您设置了filterView.clipsToBounds = true
。
func showwAndHideFilterMenu(category : Int)
if showFilterMenu == false
var filterFrame = filterView.frame
let actualHeight = filterFrame.size.height
//initially set height to zero and in animation block we need to set its actual height.
filterFrame.size.height = 0
filterView.frame = frame
UIView.animate(withDuration: 0.6, delay: 0, options: .curveEaseInOut, animations:
self.filterView.isHidden = false
self.showFilterMenu = true
//setting the actual height with animation
filterFrame.size.height = actualHeight
filterView.frame = filterFrame
) (isCompleted) in
else
var filterFrame = filterView.frame
UIView.animate(withDuration: 0.6, delay: 0, options: .curveEaseInOut, animations:
self.filterView.isHidden = true
self.showFilterMenu = false
//set the height of the filter view to 0
filterView.frame = filterFrame
filterFrame.size.height = 0
filterView.frame = frame
) (isCompleted) in
【讨论】:
【参考方案3】:试试这将使您的视图从上到下滑动,然后隐藏该视图
//MARK: Slide View - Top To Bottom
func viewSlideInFromTopToBottom(view: UIView) -> Void
let transition:CATransition = CATransition()
transition.duration = 0.5
transition.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeInEaseOut)
transition.type = CATransitionType.push
transition.subtype = CATransitionSubtype.fromBottom
view.layer.add(transition, forKey: kCATransition)
用法
// Cancel Button
@IBAction func cancelButtonAction(_ sender: Any)
self.viewSlideInFromTopToBottom(view: hideAndShowPickerView)
hideAndShowPickerView.isHidden = true
【讨论】:
以上是关于Swift 中的动画显示和隐藏视图的主要内容,如果未能解决你的问题,请参考以下文章