使用Swift(iOS)中的约束以编程方式对视图进行动画处理

您知道对我来说,应用程序开发中最有趣的部分是什么? 它正在改善用户体验(UX)。 改善用户体验的方法之一就是在应用中添加直观的动画。 我们可以通过多种方式实现这一目标,一种方式是修改如下所示的GIF之类的约束。

让我引导您完成这些简单的步骤,以实现惊人的动画效果。

首先为徽标图像定义topView。

 私人懒惰var topViewForImage:UIView = { 
让view = UIView()
view.backgroundColor = .lightGray
view.translatesAutoresizingMaskIntoConstraints = false
返回视图
}()

translatesAutoresizingMaskIntoConstraints是允许我们以编程方式向视图添加约束的一种方法。 不要忘记将其设置为false

现在该创建imageView以在topView中显示一些图像了,

 私人懒惰var topImageView:UIImageView = { 
让图像= UIImageView()
image.image = imageLiteral(resourceName:“ appLogo”)
image.contentMode = .scaleAspectFit
image.translatesAutoresizingMaskIntoConstraints = false
返回图片
}()

NSLayoutConstraints定义类型为NSLayoutConstraints的高度锚点,因为我们需要在各种事件(例如keyboardWillShow()和keyboardWillHide(),

  var heightAnchor:NSLayoutConstraint? 

现在,在ViewController中添加视图和约束。

 覆盖func viewDidLoad(){ 
super.viewDidLoad()
view.addSubview(topViewForImage)
topViewForImage.addSubview(topImageView)
addConstraintsToView()
} func addConstraintsToView(){//向topViewForImage添加约束
NSLayoutConstraint.activate([
topViewForImage.leadingAnchor.constraint(equalTo:view.leadingAnchor),topViewForImage.trailingAnchor.constraint(equalTo:view.trailingAnchor),topViewForImage.topAnchor.constraint(equalTo:view.topAnchor)
])heightAnchor = topViewForImage.heightAnchor.constraint(equalTo:view.heightAnchor,乘数:0.3)
//乘数0.3表示我们将topViewForImage的高度设置为视图高度的30%。
heightAnchor?.isActive = true //向topImageView添加约束
NSLayoutConstraint.activate([
topImageView.centerXAnchor.constraint(equalTo:topViewForImage.centerXAnchor),topImageView.centerYAnchor.constraint(equalTo:
topViewForImage.centerYAnchor),topImageView.widthAnchor.constraint(等于:topViewForImage.widthAnchor,乘数:0.7),topImageView.heightAnchor.constraint(等于:topViewForImage.heightAnchor,乘数:0.4)
])
}

您可以在addConstraintsToView()方法中看到,我们正在针对topViewForImage设置topImageView的约束。 这意味着随着topViewForImage的尺寸更改,topImageView的尺寸也随之更改(这是dope🤩)。

Husshhh…所有视图设置已完成。 现在让我们做魔术吧。 当键盘出现时,我们只需要调整topViewForImage的高度锚点即可。

  @objc fileprivate func keyboardWillShow(通知:NSNotification){ 
保护键盘=(notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as?NSValue)?. cgRectValue else {return} heightAnchor?.isActive = false
heightAnchor = topViewForImage.heightAnchor.constraint(equalToConstant:0)
heightAnchor?.isActive = true UIView.animate(withDuration:0.5){
self.view.layoutIfNeeded()
}
}

同样在keyboardWillHide()中实现以下方法,

  @objc fileprivate func keyboardWillHide(通知:NSNotification){ 
保护键盘=(notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as?NSValue)?. cgRectValue else {return}
heightAnchor = topViewForImage.heightAnchor.constraint(等于:view.heightAnchor,乘数:0.3)//将其重置为30%
heightAnchor?.isActive = true UIView.animate(withDuration:0.5,animations:{
self.view.layoutIfNeeded()
})
}

self.view.layoutIfNeeded()这使其余部分变得神奇,顾名思义,它仅在约束发生任何更改时才对视图进行布局。

我们完了。


在视图中添加动画并不是一件容易的事。 您可以根据需要尝试不同的组合来使用它。 祝一切顺利。 如果您觉得有帮助并与他人分享,请鼓掌。