【发布时间】:2019-01-14 03:14:49
【问题描述】:
我正在尝试为我的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)
}
}
【问题讨论】:
-
什么不起作用?我认为你不应该在
viewDidLoad中放置任何动画代码,因为当viewDidLoad被调用时视图甚至不可见。 -
尝试在
viewDidAppear中调用setupView。 -
对不起,我不清楚。它没有“淡入”,基本上 alpha 直接跳到 0.7
-
viewDidAppear是入门的更好选择 -
啊,是的,这很有效@iPeter - 请考虑回答这个问题,以便我将其标记为正确。非常感谢:)
标签: ios swift uiimageview ios-animations