您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

用 Swift 打造簡易外送 App 的 UI 框架實作分享

編輯:iOS 開發綜合

前言

學 Swift 也有一段時間了,陸續做過一些小 demo,一直想找機會完成一個完整專案。剛好學校附近的午餐外送逐漸流行起來——不像國內有那麼多強大的外送平台,美國雖然也有但數量不多,而且華人對它們大多不熟悉、也不太用。於是筆者決定針對午餐外送做一個 App,折騰幾天下來只完成了 UI,雖看似簡單,新手做起來東西還真不少。至於 Swift 如何與後端互動,我打算之後再慢慢研究;資料庫方面我對 SQL、MongoDB 之類的都還算熟悉。

目錄結構

這個 App 的所有 UI 都用純代碼建立(靈感來自 100 Days of Swift)。我早期練習時習慣用 storyboard,但頁面一超過十頁就開始凌亂,尤其那些 segue 連線佈滿整個畫面時。後來我改用 SnapKit 做 UI,雖比 CSS 仍略顯不便,整體使用起來還算順手。以下大致列出已實作的功能:

引導頁
午餐菜單(tableView)
購物車與動畫
下拉刷新
自訂個人主頁(collectionView)
Reminder 與 Setting 需要背景支援,暫用 Alert 簡單回應
全屏右滑退出

完整代碼請見我的 Github,以下主要展示效果並簡述實作過程,代碼中已有大量註解。

引導頁

引導頁用 collectionView 實作,一開始先判斷是否需要進入引導頁,若版本更新則進入。將 collectionView 的滑動方向設為 .horizontal,頁數可任意設定。再放一個啟動用的 startButton,前幾頁都設為 startButton.isHidden = true,到最後一頁才顯示,並加上淡入動畫。

菜單與購物車


shoppingCart

菜單支援下拉刷新,原本想自訂下拉樣式(像 ALin 的專案那樣),但遇到些問題,最後改用系統自帶的 UIRefreshControl,並在下拉時顯示更新時間、微調時間格式。代碼很簡單:

複製代碼 代碼如下:let dateString = DateFormatter.localizedString(from: NSDate() as Date, dateStyle: .medium, timeStyle: .short)
self.refreshControl.attributedTitle = NSAttributedString(string: "Last updated on \(dateString)", attributes: attributes)
self.refreshControl.tintColor = UIColor.white

接著做了一個購物車動畫:把菜單中的圖片先放大再縮小,「拋入」購物車,其實是沿著一條 UIBezierPath 路徑移動。動畫結束後,在 animationDidStop() 裡讓購物車圖片抖動,並顯示購買數量——那個 countLabel 是長寬皆為 15、位於購物車右上角的 UILabel()。

先實作一個回呼方法,點擊 cell 上的購買按鈕後觸發:

 func menuListCell(_ cell: MenuListCell, foodImageView: UIImageView) { guard let indexPath = tableView.indexPath(for: cell) else { return } // retrieve the current food model, add it to shopping cart model let model = foodArray[indexPath.section][indexPath.row] addFoodArray.append(model) // recalculate the frame of imageView, start animation var rect = tableView.rectForRow(at: indexPath) rect.origin.y -= tableView.contentOffset.y var headRect = foodImageView.frame headRect.origin.y = rect.origin.y + headRect.origin.y - 64 startAnimation(headRect, foodImageView: foodImageView) } 

點擊購買後的動畫實作:

 fileprivate func startAnimation(_ rect: CGRect, foodImageView: UIImageView) { if layer == nil { layer = CALayer() layer?.contents = foodImageView.layer.contents layer?.contentsGravity = kCAGravityResizeAspectFill layer?.bounds = rect layer?.cornerRadius = layer!.bounds.height * 0.5 layer?.masksToBounds = true layer?.position = CGPoint(x: foodImageView.center.x, y: rect.minY + 96) KeyWindow.layer.addSublayer(layer!) // animation path path = UIBezierPath() path!.move(to: layer!.position) path!.addQuadCurve(to: CGPoint(x:SCREEN_WIDTH - 25, y: 35), controlPoint: CGPoint(x: SCREEN_WIDTH * 0.5, y: rect.origin.y - 80)) } groupAnimation() } 

放大、縮小、拋入購物車的組合動畫:

 // start group animation: throw, larger, smaller image fileprivate func groupAnimation() { tableView.isUserInteractionEnabled = false // move path let animation = CAKeyframeAnimation(keyPath: "position") animation.path = path!.cgPath animation.rotationMode = kCAAnimationRotateAuto // larger image let bigAnimation = CABasicAnimation(keyPath: "transform.scale") bigAnimation.duration = 0.5 bigAnimation.fromValue = 1 bigAnimation.toValue = 2 bigAnimation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseIn) // smaller image let smallAnimation = CABasicAnimation(keyPath: "transform.scale") smallAnimation.beginTime = 0.5 smallAnimation.duration = 1 smallAnimation.fromValue = 2 smallAnimation.toValue = 0.5 smallAnimation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseOut) // group animation let groupAnimation = CAAnimationGroup() groupAnimation.animations = [animation, bigAnimation, smallAnimation] groupAnimation.duration = 1.5 groupAnimation.isRemovedOnCompletion = false groupAnimation.fillMode = kCAFillModeForwards groupAnimation.delegate = self layer?.add(groupAnimation, forKey: "groupAnimation") } 

組合動畫結束後的收尾效果:

 // end image animation, start other animations func animationDidStop(_ anim: CAAnimation, finished flag: Bool) { if anim == layer?.animation(forKey: "groupAnimation") { // start user interaction tableView.isUserInteractionEnabled = true // hide layer layer?.removeAllAnimations() layer?.removeFromSuperlayer() layer = nil // if user buy any food, show the count label if self.addFoodArray.count > 0 { addCountLabel.isHidden = false } // show the count label let goodCountAnimation = CATransition() goodCountAnimation.duration = 0.25 addCountLabel.text = "\(self.addFoodArray.count)" addCountLabel.layer.add(goodCountAnimation, forKey: nil) // shopping cart shaking let cartAnimation = CABasicAnimation(keyPath: "transform.translation.y") cartAnimation.duration = 0.25 cartAnimation.fromValue = -5 cartAnimation.toValue = 5 cartAnimation.autoreverses = true cartButton.layer.add(cartAnimation, forKey: nil) } } 

購物車內可增減購買數量,總價會隨之動態更新。關鍵在於兩個東西:一個是 selected 變量,一個是 reCalculateCount() 函數。依 selected 決定最終總價,若有變動就重新計算(reCalculateCount)。

 fileprivate func reCalculateCount() { for model in addFoodArray! { if model.selected == true { price += Float(model.count) * (model.vipPrice! as NSString).floatValue } } // assign price let attributeText = NSMutableAttributedString(string: "Subtotal: \(self.price)") attributeText.setAttributes([NSForegroundColorAttributeName: UIColor.red], range: NSMakeRange(5, attributeText.length - 5)) totalPriceLabel.attributedText = attributeText price = 0 tableView.reloadData() } 

尚未實作 Pay() 功能,打算之後嘗試 Apple Pay。以前用慣了支付寶,剛到美國時頗不適應——其實很多地方國內都已經領先美國不少,還好現在有了 Apple Pay,整體還算好用。

自訂個人主頁


profile

原本想做成簡書那樣,但對新手來說稍有難度;加上這個 App 並無必要實作那些功能,便沒有深入研究。

如前所述,這一頁同樣用 collectionView,共兩個 section:上方是 UserCollectionViewCell,下方是 HistoryCollectionViewCell。下方這個 section 類似 table 的 section,有一個會自動懸浮的 header,該 header 採用 ALin 大神的輪子 LevitateHeaderFlowLayout(),當然版權歸原作者所有。

 class CollectionViewFlowLayout: LevitateHeaderFlowLayout { override func prepare() { super.prepare() collectionView?.alwaysBounceVertical = true scrollDirection = .vertical minimumLineSpacing = 5 minimumInteritemSpacing = 0 } } 

整體而言這個專案規模不大,若再把後端補上,也算是一個相當完整的小專案了。

以上便是本文的全部內容,希望對大家的學習有所幫助,也感謝各位的支持!

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved