本文為參考學習的文章,在閱讀這位作者的源碼之后學習到的一個小方法。
解決方案
在 iOS 中,為應用設置啟動頁非常簡單。按照 Apple 的意思,啟動頁應當盡可能的與首屏相似,并且盡可能的避免使用啟動動畫。但是有時候我們想讓啟動頁稍微豐富一些,為它添加一些事情。
在之前,我的做法是(OC)
在 AppDelegate 中的
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions;
方法中添加動畫效果,具體實現如下:
- 獲取 LaunchScreen 中的 view(這需要你的應用啟動頁設置為 LaunchScreen)
UIViewController *viewController = [[UIStoryboard storyboardWithName:@"LaunchScreen" bundle:nil] instantiateViewControllerWithIdentifier:@"LaunchScreen"];
UIView *launchView = viewController.view;
- 將 view 添加到 window 上
[self.window addSubview:launchView];
- 實現 view 的動畫
[UIView animateWithDuration:1.3f delay:0.1f options:UIViewAnimationOptionBeginFromCurrentState animations:^{
launchView.alpha = 0.0f;
launchView.layer.transform = CATransform3DScale(CATransform3DIdentity, 1.3f, 1.3f, 1.0f);
} completion:^(BOOL finished) {
[launchView removeFromSuperview];
}];
這里將 view 放大顯示并且同時消失,記得在動畫結束時將 view 移除掉。
新的小方法是(swift)
上述方法將啟動頁的 ViewController 拿到,所以可以將其上的多個控件一起處理,形成比較和諧的效果。但是也有很多啟動頁都由一張圖片構成,所以在這里,我們可以直接拿到圖片,進行處理。
- 一個獲取啟動圖片的函數(這謎一般的對齊)
func launchImage() -> UIImage {
var launchImage : UIImage!
var viewOrientation : String!
let viewSize = UIScreen.main.bounds.size
let orientation = UIApplication.shared.statusBarOrientation
// 獲取屏幕方向
if orientation == .landscapeLeft || orientation == .landscapeRight {
viewOrientation = "Landscape"
} else {
viewOrientation = "Portrait"
}
let imagesInfo = Bundle.main.infoDictionary!["UILaunchImages"]
for dic: Dictionary<String, String> in imagesInfo as! Array {
let imageSize = CGSizeFromString(dic["UILaunchImageSize"]!)
if imageSize.equalTo(viewSize) && viewOrientation == dic["UILaunchImageOrientation"]! as String {
launchImage = UIImage(named: dic["UILaunchImageName"]!)
}
}
return launchImage
}
在這里,獲取的是 Assets 中的啟動頁。
- 在 viewDidLoad() 中添加 UIImageView,設置圖片
override func viewDidLoad() {
super.viewDidLoad()
// 添加啟動頁
let launchImageView = UIImageView(frame: self.view.bounds)
launchImageView.image = self.launchImage()
view.addSubview(launchImageView)
UIView.animate(withDuration: 1, delay: 1, options: .curveEaseIn, animations: {
launchImageView.transform = CGAffineTransform(scaleX: 1.5, y: 1.5)
launchImageView.alpha = 0
}) { (finished) in
launchImageView.removeFromSuperview()
}
}
- 動畫處理,同上。
遇到的問題
在處理第二種方案時,發現這個動畫只能加在 Initial View Controller 中,否則動畫沒有效果。
總結
其實在 LaunchScreen 配置啟動頁較為簡便,只需要一個圖片即可,并且可以控制各個控件,相對靈活。但是剛剛打開之前的代碼運行時發現一個問題。。。各取所需吧。