我正在尝试制作HomeController
的背景图片的动画。
我希望淡入图像,因此我希望为其alpha
属性设置动画。
我在这里找到了很多答案,但是似乎有些过时了(obj c,iOS 3/4/5等),按照推荐的方法,我仍然无法使该动画正常工作。
有人可以告诉我我的代码有什么问题吗?
我想制作backgroundImage
的动画。我已将动画代码放在setupView
方法的末尾。
它并没有像我所希望的那样“淡入”,基本上alpha会直接跳到0.7
import UIKit
class HomeController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
setupView()
}
private let backgroundImage: UIImageView = {
let image = UIImageView()
image.image = #imageLiteral(resourceName: "foggy").withRenderingMode(.alwaysOriginal)
image.contentMode = .scaleToFill
image.alpha = 0
image.isOpaque = false
return image
}()
private let currentLocation: UIButton = {
let button = UIButton(type: .system)
button.setTitle("Southampton, UK", for: .normal)
button.titleLabel?.font = UIFont.systemFont(ofSize: 24)
button.contentMode = .center
button.setTitleColor(.black, for: .normal)
button.addTarget(self, action: #selector(onPressLocation), for: .touchUpInside)
return button
}()
private let currentTemp: UIButton = {
let button = UIButton(type: .system)
button.setTitle("37°C", for: .normal)
button.titleLabel?.font = UIFont.systemFont(ofSize: 54, weight: .thin)
button.contentMode = .center
button.setTitleColor(.white, for: .normal)
button.addTarget(self, action: #selector(onPressTemp), for: .touchUpInside)
return button
}()
}
extension HomeController {
@objc fileprivate func onPressLocation() -> Void {
print("Location pressed.")
}
@objc fileprivate func onPressTemp() -> Void {
self.currentTemp.setTitle("98°F", for: .normal)
}
fileprivate func setupView() -> Void {
view.backgroundColor = .white
// MARK: Background Image
view.addSubview(backgroundImage)
backgroundImage.anchor(
top: view.safeAreaLayoutGuide.topAnchor,
left: view.safeAreaLayoutGuide.leftAnchor,
bottom: view.safeAreaLayoutGuide.bottomAnchor,
right: view.safeAreaLayoutGuide.rightAnchor,
paddingTop: 0,
paddingLeft: 0,
paddingBottom: 0,
paddingRight: 0,
width: 0,
height: 0
)
// MARK: Current Location
view.addSubview(currentLocation)
currentLocation.anchor(
top: view.safeAreaLayoutGuide.topAnchor,
left: view.safeAreaLayoutGuide.leftAnchor,
right: view.safeAreaLayoutGuide.rightAnchor,
paddingTop: 50,
paddingLeft: 0,
paddingBottom: 0,
paddingRight: 0,
width: 0,
height: 26,
centerX: view.centerXAnchor
)
// MARK: Temp Button
view.addSubview(currentTemp)
currentTemp.anchor(
top: currentLocation.bottomAnchor,
paddingTop: 10,
paddingLeft: 0,
paddingBottom: 0,
paddingRight: 0,
width: 200,
height: 70,
centerX: view.centerXAnchor
)
// MARK: Animations
UIView.animate(withDuration: 6, delay: 3, options: .curveEaseInOut, animations: {
self.backgroundImage.alpha = 0.7
}, completion: nil)
}
}
答案 0 :(得分:1)
IBOutlets
在调用viewDidLoad
时不可见,因此请在setupView
中调用您的viewDidAppear
方法,这是在视图显示在屏幕上之后调用的。
希望这会有所帮助。
答案 1 :(得分:1)
您可以将代码放入任何动画作品的 viewDidAppear 视图生命周期方法中,因为viewDidAppear方法会通知视图控制器其视图已添加到视图层次结构中。请使用以下代码作为解决方案。
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated: animated)
//Call method like this
setupView()
}